GetStatusAsync(CancellationToken cancellationToken)
+ {
+ if (session is null) return new("powerpoint", "unsupported", new("Kræver Windows.", "Requires Windows."));
+ try
+ {
+ var snapshot = await session.ReadAsync(cancellationToken);
+ return new("powerpoint", "ready", new("Slideshow tilsluttet.", "Slideshow connected."), Wire.Data(snapshot));
+ }
+ catch (SlideShowUnavailableException error)
+ {
+ return new("powerpoint", "unavailable", FailureMessage(error.Reason), Wire.Data(new { reason = FailureCode(error.Reason) }));
+ }
+ }
+
+ private static string FailureCode(SlideShowFailure reason) => reason switch
+ {
+ SlideShowFailure.NotRegistered => "powerpoint_not_found",
+ SlideShowFailure.NoSlideshow => "no_slideshow",
+ SlideShowFailure.MultipleSlideshows => "multiple_slideshows",
+ _ => "powerpoint_unavailable"
+ };
+
+ private static LocalizedText FailureMessage(SlideShowFailure reason) => reason switch
+ {
+ SlideShowFailure.NotRegistered => new("PowerPoint kunne ikke findes. Åbn PowerPoint og start ét slideshow; vent, til programmet er klar.",
+ "PowerPoint could not be found. Open PowerPoint and start one slideshow; wait until it is ready."),
+ SlideShowFailure.NoSlideshow => new("PowerPoint er åbent, men intet slideshow kører. Start visningen i PowerPoint.",
+ "PowerPoint is open, but no slideshow is running. Start the slideshow in PowerPoint."),
+ SlideShowFailure.MultipleSlideshows => new("Flere slideshows kører. Afslut de ekstra visninger, så kun ét slideshow er aktivt.",
+ "Multiple slideshows are running. End the extra shows so exactly one remains active."),
+ _ => new("PowerPoint-forbindelsen er utilgængelig. Luk eventuelle dialoger i PowerPoint og kontrollér status igen.",
+ "The PowerPoint connection is unavailable. Close any PowerPoint dialogs and check status again.")
+ };
+
+ public ValueTask DisposeAsync() => session?.DisposeAsync() ?? ValueTask.CompletedTask;
+}
+public enum SlideShowFailure { ConnectionUnavailable, NotRegistered, NoSlideshow, MultipleSlideshows }
+public sealed class SlideShowUnavailableException(SlideShowFailure reason = SlideShowFailure.ConnectionUnavailable) : Exception
+{
+ public SlideShowFailure Reason { get; } = reason;
+}
diff --git a/Plugins/PowerPoint/README.md b/Plugins/PowerPoint/README.md
new file mode 100644
index 0000000..910563f
--- /dev/null
+++ b/Plugins/PowerPoint/README.md
@@ -0,0 +1,11 @@
+# PowerPoint
+
+## Dansk
+Implementeret COM-adapter; fysisk Office-test afventer. Kun eksisterende slideshow, ingen filoperationer.
+
+Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md).
+
+## English
+Implemented COM adapter; physical Office testing pending. Existing slideshow only, no file operations.
+
+See [setup](../../docs/setup.en.md), [architecture](../../docs/project.en.md), [protocol](../../docs/protocol.en.md) and [test plan](../../docs/testing.en.md).
diff --git a/Plugins/StreamDeck/README.md b/Plugins/StreamDeck/README.md
new file mode 100644
index 0000000..680530b
--- /dev/null
+++ b/Plugins/StreamDeck/README.md
@@ -0,0 +1,11 @@
+# StreamDeck
+
+## Dansk
+Implementeret plugin med 12 handlinger og officiel `.streamDeckPlugin`-installationspakke. Indlæsning er verificeret i Stream Deck; samlet praktisk PowerPoint/OBS-accept afventer. Windows-installationspakken indeholder pluginpakken.
+
+Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md).
+
+## English
+Implemented plugin with 12 actions and an official `.streamDeckPlugin` installation package. Loading has been verified in Stream Deck; complete practical PowerPoint/OBS acceptance remains pending. The Windows installer includes the plugin package.
+
+See [setup](../../docs/setup.en.md), [architecture](../../docs/project.en.md), [protocol](../../docs/protocol.en.md) and [test plan](../../docs/testing.en.md).
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/actions.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/actions.js
new file mode 100644
index 0000000..9c45502
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/actions.js
@@ -0,0 +1,113 @@
+"use strict";
+const { randomUUID } = require("node:crypto");
+const definitions = {
+ "next": {
+ "plugin": "powerpoint",
+ "action": "next",
+ "da": "Næste slide",
+ "en": "Next slide"
+ },
+ "previous": {
+ "plugin": "powerpoint",
+ "action": "previous",
+ "da": "Forrige slide",
+ "en": "Previous slide"
+ },
+ "goto": {
+ "plugin": "powerpoint",
+ "action": "goto",
+ "da": "Gå til slide",
+ "en": "Go to slide"
+ },
+ "black": {
+ "plugin": "powerpoint",
+ "action": "black",
+ "da": "Sort skærm",
+ "en": "Black screen"
+ },
+ "resume": {
+ "plugin": "powerpoint",
+ "action": "resume",
+ "da": "Vis slideshow",
+ "en": "Resume slideshow"
+ },
+ "scene": {
+ "plugin": "obs",
+ "action": "scene.switch",
+ "da": "Skift scene",
+ "en": "Switch scene"
+ },
+ "recordstart": {
+ "plugin": "obs",
+ "action": "record.start",
+ "da": "Start optagelse",
+ "en": "Start recording"
+ },
+ "recordstop": {
+ "plugin": "obs",
+ "action": "record.stop",
+ "da": "Stop optagelse",
+ "en": "Stop recording"
+ },
+ "streamstart": {
+ "plugin": "obs",
+ "action": "stream.start",
+ "da": "Start udsendelse",
+ "en": "Start streaming"
+ },
+ "streamstop": {
+ "plugin": "obs",
+ "action": "stream.stop",
+ "da": "Stop udsendelse",
+ "en": "Stop streaming"
+ },
+ "mute": {
+ "plugin": "obs",
+ "action": "input.mute",
+ "da": "Lyd fra/til",
+ "en": "Set input mute"
+ },
+ "status": {
+ "plugin": null,
+ "action": null,
+ "da": "Status",
+ "en": "Status"
+ }
+};
+function definition(uuid) {
+ const prefix = "dk.thebonden.controlhub.";
+ if (!uuid.startsWith(prefix)) throw new Error("Unknown action / Ukendt handling");
+ const item = definitions[uuid.slice(prefix.length)];
+ if (!item) throw new Error("Unknown action / Ukendt handling");
+ return item;
+}
+function makeCommand(uuid, settings, id = randomUUID()) {
+ const item = definition(uuid);
+ if (!item.plugin) throw new Error("Status is read-only / Status er skrivebeskyttet");
+ let args = {};
+ if (item.action === "goto") {
+ const slide = Number(settings.slide);
+ if (!Number.isSafeInteger(slide) || slide < 1) throw new Error("Invalid slide / Ugyldig slide");
+ args = { slide };
+ }
+ if (item.action === "scene.switch") {
+ if (typeof settings.sceneName !== "string" || !settings.sceneName.trim()) throw new Error("Missing scene / Scene mangler");
+ args = { sceneName: settings.sceneName };
+ }
+ if (item.action === "input.mute") {
+ if (typeof settings.inputName !== "string" || !settings.inputName.trim() || typeof settings.muted !== "boolean")
+ throw new Error("Invalid input / Ugyldig lydkilde");
+ args = { inputName: settings.inputName, muted: settings.muted };
+ }
+ return { protocolVersion: "1", id, plugin: item.plugin, action: item.action, arguments: args };
+}
+function statusTitle(status, language = "da") {
+ if (status.protocolVersion !== "1" || !Array.isArray(status.plugins)) throw new Error("Invalid status");
+ const ppt = status.plugins.find(p => p.id === "powerpoint");
+ const obs = status.plugins.find(p => p.id === "obs");
+ const position = ppt?.state === "ready" ? ppt.data?.position ?? "?" : "?";
+ const recording = obs?.state === "ready" ? (obs.data?.recording?.outputActive === true ? "ON" : obs.data?.recording?.outputActive === false ? "OFF" : "?") : "?";
+ const streaming = obs?.state === "ready" ? (obs.data?.streaming?.outputActive === true ? "ON" : obs.data?.streaming?.outputActive === false ? "OFF" : "?") : "?";
+ return "PPT " + position + "\n" + (language === "da" ? "OPT " : "REC ") + recording + "\nLIVE " + streaming;
+}
+module.exports = { definitions, definition, makeCommand, statusTitle };
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action.svg
new file mode 100644
index 0000000..ef09f8e
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action@2x.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action@2x.svg
new file mode 100644
index 0000000..575a8ef
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action@2x.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key.svg
new file mode 100644
index 0000000..2eac269
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key@2x.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key@2x.svg
new file mode 100644
index 0000000..0e2210a
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key@2x.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.png b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.png
new file mode 100644
index 0000000..70ab2ad
Binary files /dev/null and b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.png differ
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.svg
new file mode 100644
index 0000000..d2c0b38
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.png b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.png
new file mode 100644
index 0000000..005cd0a
Binary files /dev/null and b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.png differ
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.svg b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.svg
new file mode 100644
index 0000000..3a77d83
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.svg
@@ -0,0 +1 @@
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js
new file mode 100644
index 0000000..77d1817
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js
@@ -0,0 +1,82 @@
+"use strict";
+const { definition, makeCommand, statusTitle } = require("./actions.js");
+const { connectionReport, failure } = require("./diagnostics.js");
+function createBridge(send, fetchImpl = fetch) {
+ const contexts = new Map();
+ const busy = new Set();
+ const checking = new Set();
+ function title(context, text) { send({ event: "setTitle", context, payload: { title: text, target: 0 } }); }
+ function current(context, item) { return contexts.get(context) === item; }
+ function validToken(token) { return typeof token === "string" && token.length >= 32 && token.length <= 4096; }
+ async function checkConnection(message) {
+ const item = contexts.get(message.context);
+ if (!item || item.action !== message.action || checking.has(message.context) ||
+ message.payload?.kind !== "checkConnection" || typeof message.payload.requestId !== "string" ||
+ message.payload.requestId.length > 64) return;
+ checking.add(message.context);
+ let report;
+ try {
+ const token = message.payload.token;
+ if (!validToken(token)) report = failure("invalid_token");
+ else {
+ const response = await fetchImpl("http://127.0.0.1:5187/api/v1/status", {
+ method: "GET", headers: { Authorization: "Bearer " + token },
+ signal: AbortSignal.timeout(35000), redirect: "error"
+ });
+ report = !response.ok ? failure(response.status === 401 ? "unauthorized" : response.status === 429 ? "busy" : "unreachable") :
+ connectionReport(await response.json());
+ }
+ } catch { report = failure("unreachable"); }
+ finally { checking.delete(message.context); }
+ if (current(message.context, item)) send({ event: "sendToPropertyInspector", context: message.context,
+ payload: { kind: "connectionResult", requestId: message.payload.requestId, ...report } });
+ }
+ async function invoke(context) {
+ const item = contexts.get(context);
+ if (!item || busy.has(context)) return;
+ busy.add(context);
+ try {
+ const settings = item.settings;
+ if (!validToken(settings.token)) throw new Error("Token missing / Token mangler");
+ const isStatus = item.action === "dk.thebonden.controlhub.status";
+ const command = isStatus ? null : makeCommand(item.action, settings);
+ const response = await fetchImpl("http://127.0.0.1:5187/api/v1/" + (isStatus ? "status" : "commands"), {
+ method: isStatus ? "GET" : "POST",
+ headers: { Authorization: "Bearer " + settings.token, "Content-Type": "application/json" },
+ ...(command ? { body: JSON.stringify(command) } : {}),
+ signal: AbortSignal.timeout(isStatus ? 35000 : 12000),
+ redirect: "error"
+ });
+ if (!response.ok) throw new Error("HTTP error / HTTP-fejl");
+ const result = await response.json();
+ if (!current(context, item)) return;
+ if (isStatus) {
+ title(context, statusTitle(result, settings.language));
+ } else {
+ if (result.protocolVersion !== "1" || result.id !== command.id || result.success !== true) throw new Error("Command failed / Kommando fejlede");
+ title(context, definition(item.action)[settings.language === "en" ? "en" : "da"]);
+ send({ event: "showOk", context });
+ }
+ } catch {
+ if (current(context, item)) {
+ title(context, item.settings.language === "en" ? "Check\nstatus" : "Tjek\nstatus");
+ send({ event: "showAlert", context });
+ }
+ } finally { busy.delete(context); }
+ }
+ async function handle(message) {
+ if (message.event === "willDisappear") { contexts.delete(message.context); return; }
+ if (message.event === "willAppear" || message.event === "didReceiveSettings") {
+ definition(message.action);
+ contexts.set(message.context, { action: message.action, settings: message.payload?.settings ?? {} });
+ if (message.action === "dk.thebonden.controlhub.status") await invoke(message.context);
+ }
+ if (message.event === "sendToPlugin") await checkConnection(message);
+ if (message.event === "keyDown") await invoke(message.context);
+ }
+ async function poll() {
+ await Promise.all([...contexts].filter(([,v]) => v.action === "dk.thebonden.controlhub.status").map(([id]) => invoke(id)));
+ }
+ return { handle, poll };
+}
+module.exports = { createBridge };
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js
new file mode 100644
index 0000000..a10f108
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js
@@ -0,0 +1,60 @@
+"use strict";
+// Faste, lokale tekster ud fra kendte årsager; vis aldrig rå serverfejl.
+// Fixed local text for known reasons; never display raw server errors.
+const issues = {
+ powerpoint: {
+ powerpoint_not_found: ["PowerPoint kunne ikke findes. Åbn programmet og start ét slideshow.", "PowerPoint could not be found. Open it and start one slideshow."],
+ no_slideshow: ["PowerPoint er åbent, men intet slideshow kører. Start visningen.", "PowerPoint is open, but no slideshow is running. Start the show."],
+ multiple_slideshows: ["Flere slideshows kører. Lad kun ét slideshow være aktivt.", "Multiple slideshows are running. Leave exactly one show active."],
+ powerpoint_unavailable: ["PowerPoint svarer ikke. Luk eventuelle dialoger og prøv status igen.", "PowerPoint is unavailable. Close any dialogs and check status again."]
+ },
+ obs: {
+ connection_unavailable: ["OBS kan ikke kontaktes. Start OBS, aktivér WebSocket-serveren og kontrollér porten.", "OBS cannot be reached. Start OBS, enable its WebSocket server and check the port."],
+ password_missing: ["OBS kræver en adgangskode. Stop Control Hub, indtast den og start igen.", "OBS requires a password. Stop Control Hub, enter it and start again."],
+ authentication_failed: ["OBS afviste adgangskoden. Stop Control Hub, ret adgangskoden og start igen.", "OBS rejected the password. Stop Control Hub, correct the password and start again."],
+ protocol_error: ["Svaret passer ikke til OBS WebSocket v5. Kontrollér server og port.", "The reply is not compatible with OBS WebSocket v5. Check the server and port."],
+ connection_lost: ["OBS-forbindelsen blev afbrudt. Kontrollér status før en ny handling.", "The OBS connection was interrupted. Check status before another action."],
+ request_rejected: ["OBS afviste forespørgslen. Kontrollér scenenavn, lydkilde og status.", "OBS rejected the request. Check the scene name, audio input and status."]
+ }
+};
+const failures = {
+ invalid_token: ["Indsæt et token på mindst 32 tegn.", "Enter a token of at least 32 characters."],
+ unauthorized: ["Token blev afvist af Control Hub.", "Control Hub rejected the token."],
+ busy: ["Control Hub er optaget. Prøv forbindelsestesten igen senere.", "Control Hub is busy. Try the connection check again later."],
+ unreachable: ["Control Hub kunne ikke kontaktes. Kontrollér, at værten kører.", "Could not reach Control Hub. Check that the host is running."],
+ invalid_response: ["Control Hub returnerede en ukendt statusprotokol.", "Control Hub returned an unrecognized status protocol."]
+};
+function failure(code) {
+ const [da, en] = failures[code] ?? failures.unreachable;
+ return { code, message: { da, en }, checks: [] };
+}
+function connectionReport(status) {
+ if (status?.protocolVersion !== "1" || typeof status.version !== "string" ||
+ !/^\d+\.\d+\.\d+$/.test(status.version) || !Array.isArray(status.plugins))
+ return failure("invalid_response");
+ const checks = [];
+ for (const id of ["powerpoint", "obs"]) {
+ const matches = status.plugins.filter(p => p?.id === id);
+ if (matches.length !== 1 || !["ready", "unavailable", "unsupported", "not_implemented"].includes(matches[0].state))
+ return failure("invalid_response");
+ const state = matches[0].state;
+ const ready = state === "ready";
+ let message = id === "powerpoint" ?
+ { da: ready ? "PowerPoint: slideshow tilsluttet." : "PowerPoint: start ét slideshow, eller kontrollér forbindelsen.",
+ en: ready ? "PowerPoint: slideshow connected." : "PowerPoint: start one slideshow or check the connection." } :
+ { da: ready ? "OBS: tilsluttet." : "OBS: kontrollér WebSocket-server, port og adgangskode.",
+ en: ready ? "OBS: connected." : "OBS: check the WebSocket server, port and password." };
+ const reason = matches[0].data?.reason;
+ if (!ready && typeof reason === "string" && Object.hasOwn(issues[id], reason)) {
+ const [da, en] = issues[id][reason];
+ message = { da, en };
+ }
+ checks.push({ id, state, message });
+ }
+ const ready = checks.every(c => c.state === "ready");
+ return { code: ready ? "ready" : "partial", version: status.version,
+ message: ready ? { da: "Control Hub, PowerPoint og OBS svarer.", en: "Control Hub, PowerPoint and OBS are responding." } :
+ { da: "Control Hub svarer; en eller flere integrationer er utilgængelige.",
+ en: "Control Hub is responding; one or more integrations are unavailable." }, checks };
+}
+module.exports = { connectionReport, failure };
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html
new file mode 100644
index 0000000..1359dd1
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html
@@ -0,0 +1,11 @@
+
+Control Hub
+
+Sprog / Language Dansk English
+
+
+
+
+Lyd fra / Mute Lyd til / Unmute
+
+
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js
new file mode 100644
index 0000000..b29171a
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js
@@ -0,0 +1,91 @@
+"use strict";
+let socket, context, actionContext, currentSettings = {}, action, pendingCheck = null, checkTimer, lastReport = null;
+const el = id => document.getElementById(id);
+const translations = {
+ da: { tokenLabel: "Control Hub-adgangstoken", slideLabel: "Slidenummer (fra 1)", sceneLabel: "Præcist scenenavn i OBS", inputLabel: "Præcist navn på lydkilde i OBS", muteLabel: "Ønsket lydtilstand",
+ hint: "Kører kun lokalt. Token gemmes i Stream Deck-indstillinger. Del ikke profiler med token. Forbindelsestesten læser kun status og bruger tokenet i feltet uden at gemme det.",
+ save: "Gem", check: "Test forbindelse", saved: "Gemt", checking: "Kontrollerer Control Hub, PowerPoint og OBS…",
+ timeout: "Forbindelsestesten svarede ikke. Kontrollér, at Control Hub kører.", disconnected: "Forbindelsen til Stream Deck er afbrudt." },
+ en: { tokenLabel: "Control Hub access token", slideLabel: "Slide number (starting at 1)", sceneLabel: "Exact OBS scene name", inputLabel: "Exact OBS input name", muteLabel: "Desired mute state",
+ hint: "Local use only. Token is stored in Stream Deck settings. Do not share profiles containing it. The connection check only reads status and uses the entered token without saving it.",
+ save: "Save", check: "Test connection", saved: "Saved", checking: "Checking Control Hub, PowerPoint and OBS…",
+ timeout: "The connection check did not respond. Check that Control Hub is running.", disconnected: "Disconnected from Stream Deck." }
+};
+function language() { return el("language").value === "en" ? "en" : "da"; }
+function showReport() {
+ if (!lastReport) return;
+ const lang = language();
+ const lines = [lastReport.message?.[lang] ?? translations[lang].timeout];
+ if (lastReport.version) lines.push("Control Hub " + lastReport.version);
+ for (const check of lastReport.checks ?? []) if (check.message?.[lang]) lines.push(check.message[lang]);
+ el("connection").textContent = lines.join("\n");
+}
+function render() {
+ const lang = language();
+ document.documentElement.lang = lang;
+ for (const id of ["tokenLabel","slideLabel","sceneLabel","inputLabel","muteLabel","hint","save","check"])
+ el(id).textContent = translations[lang][id];
+ if (pendingCheck) el("connection").textContent = translations[lang].checking;
+ else showReport();
+}
+function clearCheck() {
+ clearTimeout(checkTimer);
+ pendingCheck = null;
+ const disconnected = !socket || socket.readyState !== WebSocket.OPEN;
+ el("check").disabled = disconnected;
+ el("save").disabled = disconnected;
+}
+function invalidateCheck() {
+ clearCheck(); lastReport = null; el("connection").textContent = ""; el("saved").textContent = "";
+}
+function load(settings) {
+ currentSettings = settings;
+ invalidateCheck();
+ for (const key of ["token", "slide", "sceneName", "inputName"]) el(key).value = settings[key] ?? "";
+ el("language").value = settings.language === "en" ? "en" : "da";
+ el("muted").value = settings.muted === false ? "false" : "true";
+ render();
+}
+function connectElgatoStreamDeckSocket(port, uuid, registerEvent, info, actionInfo) {
+ const data = JSON.parse(actionInfo);
+ // Send with the UI registration UUID; replies identify the key instance.
+ // Send med UI-registrerings-id; svar identificerer den konkrete knap.
+ context = uuid; actionContext = data.context; action = data.action;
+ if (typeof actionContext !== "string" || !actionContext) throw new Error("Missing action context / Knapkontekst mangler");
+ load(data.payload?.settings ?? {});
+ el("slideField").hidden = !action.endsWith(".goto");
+ el("sceneField").hidden = !action.endsWith(".scene");
+ el("inputField").hidden = !action.endsWith(".mute");
+ socket = new WebSocket("ws://127.0.0.1:" + port);
+ socket.onopen = () => { socket.send(JSON.stringify({ event: registerEvent, uuid })); clearCheck(); };
+ socket.onclose = () => { clearCheck(); el("connection").textContent = translations[language()].disconnected; };
+ socket.onmessage = event => {
+ let message;
+ try { message = JSON.parse(event.data); } catch { return; }
+ const forThisInspector = message.context === actionContext || message.context === context;
+ if (message.event === "didReceiveSettings" && forThisInspector) load(message.payload.settings);
+ if (message.event === "sendToPropertyInspector" && forThisInspector &&
+ message.payload?.kind === "connectionResult" && pendingCheck && message.payload.requestId === pendingCheck) {
+ clearCheck(); lastReport = message.payload; showReport();
+ }
+ };
+}
+el("language").onchange = render;
+el("token").oninput = invalidateCheck;
+el("save").onclick = () => {
+ if (!socket || socket.readyState !== WebSocket.OPEN || pendingCheck) return;
+ const settings = { ...currentSettings, token: el("token").value, language: language(),
+ slide: el("slide").value, sceneName: el("sceneName").value, inputName: el("inputName").value, muted: el("muted").value === "true" };
+ socket.send(JSON.stringify({ event: "setSettings", action, context, payload: settings }));
+ el("saved").textContent = translations[settings.language].saved;
+};
+el("check").onclick = () => {
+ if (!socket || socket.readyState !== WebSocket.OPEN || pendingCheck) return;
+ pendingCheck = crypto.randomUUID(); lastReport = null;
+ el("check").disabled = true; el("save").disabled = true;
+ el("connection").textContent = translations[language()].checking;
+ socket.send(JSON.stringify({ event: "sendToPlugin", action, context,
+ payload: { kind: "checkConnection", requestId: pendingCheck, token: el("token").value } }));
+ checkTimer = setTimeout(() => { clearCheck(); el("connection").textContent = translations[language()].timeout; }, 40000);
+};
+render();
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/manifest.json b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/manifest.json
new file mode 100644
index 0000000..a7b8b3f
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/manifest.json
@@ -0,0 +1,232 @@
+{
+ "$schema": "https://schemas.elgato.com/streamdeck/plugins/manifest.json",
+ "Name": "Control Hub",
+ "Version": "0.0.1.0",
+ "Author": "thebonden",
+ "Description": "Styr PowerPoint og OBS via Control Hub / Control PowerPoint and OBS through Control Hub.",
+ "UUID": "dk.thebonden.controlhub",
+ "SDKVersion": 2,
+ "CodePath": "plugin.js",
+ "Nodejs": {
+ "Version": "24"
+ },
+ "Software": {
+ "MinimumVersion": "7.4"
+ },
+ "OS": [
+ {
+ "Platform": "windows",
+ "MinimumVersion": "10"
+ }
+ ],
+ "Icon": "assets/plugin",
+ "Category": "Control Hub",
+ "CategoryIcon": "assets/action",
+ "PropertyInspectorPath": "inspector.html",
+ "Actions": [
+ {
+ "UUID": "dk.thebonden.controlhub.next",
+ "Name": "Næste slide / Next slide",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Næste slide",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Næste slide / Next slide"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.previous",
+ "Name": "Forrige slide / Previous slide",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Forrige slide",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Forrige slide / Previous slide"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.goto",
+ "Name": "Gå til slide / Go to slide",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Gå til slide",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Gå til slide / Go to slide"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.black",
+ "Name": "Sort skærm / Black screen",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Sort skærm",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Sort skærm / Black screen"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.resume",
+ "Name": "Vis slideshow / Resume slideshow",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Vis slideshow",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Vis slideshow / Resume slideshow"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.scene",
+ "Name": "Skift scene / Switch scene",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Skift scene",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Skift scene / Switch scene"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.recordstart",
+ "Name": "Start optagelse / Start recording",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Start optagelse",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Start optagelse / Start recording"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.recordstop",
+ "Name": "Stop optagelse / Stop recording",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Stop optagelse",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Stop optagelse / Stop recording"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.streamstart",
+ "Name": "Start udsendelse / Start streaming",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Start udsendelse",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Start udsendelse / Start streaming"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.streamstop",
+ "Name": "Stop udsendelse / Stop streaming",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Stop udsendelse",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Stop udsendelse / Stop streaming"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.mute",
+ "Name": "Lyd fra/til / Set input mute",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Lyd fra/til",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Lyd fra/til / Set input mute"
+ },
+ {
+ "UUID": "dk.thebonden.controlhub.status",
+ "Name": "Status / Status",
+ "Icon": "assets/action",
+ "Controllers": [
+ "Keypad"
+ ],
+ "SupportedInMultiActions": false,
+ "States": [
+ {
+ "Image": "assets/key",
+ "Title": "Status",
+ "FontSize": 11
+ }
+ ],
+ "Tooltip": "Status / Status"
+ }
+ ]
+}
diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/plugin.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/plugin.js
new file mode 100644
index 0000000..1c3a36d
--- /dev/null
+++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/plugin.js
@@ -0,0 +1,22 @@
+"use strict";
+const { createBridge } = require("./bridge.js");
+const args = process.argv.slice(2);
+function argument(name) {
+ const index = args.indexOf(name);
+ if (index < 0 || !args[index + 1]) throw new Error("Missing Stream Deck argument / Stream Deck-argument mangler");
+ return args[index + 1];
+}
+const port = Number(argument("-port"));
+if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid port / Ugyldig port");
+const uuid = argument("-pluginUUID");
+const registerEvent = argument("-registerEvent");
+const socket = new WebSocket("ws://127.0.0.1:" + port);
+const send = message => { if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message)); };
+const bridge = createBridge(send);
+socket.addEventListener("open", () => send({ event: registerEvent, uuid }));
+socket.addEventListener("message", event => {
+ try { void bridge.handle(JSON.parse(event.data)).catch(() => {}); } catch {}
+});
+const interval = setInterval(() => { void bridge.poll(); }, 3000);
+socket.addEventListener("close", () => { clearInterval(interval); process.exit(0); });
+socket.addEventListener("error", () => { clearInterval(interval); process.exit(1); });
diff --git a/README.en.md b/README.en.md
new file mode 100644
index 0000000..7779541
--- /dev/null
+++ b/README.en.md
@@ -0,0 +1,70 @@
+# Control Hub · 0.0.001
+
+[Dansk](README.md) · **English**
+
+Control Hub is a local control centre for presentations, production and live operation. The first priority is **Stream Deck → PowerPoint and OBS Studio**, followed by **AndroidRemote**.
+
+The goal is to give operators clear buttons, predictable commands and truthful status, including when an application is unavailable. Control uses application interfaces; no feature depends on the focused window.
+
+> **Development version, not a release.** 0.0.001 includes an executable .NET 10 core, concrete PowerPoint and OBS adapters, and a Stream Deck plugin. Automated tests do not replace trials with physical Stream Deck hardware, Office and OBS. See the [test plan](docs/testing.en.md) and the PR's build results.
+
+## Documentation
+
+- [Detailed project description](docs/project.en.md) · [Dansk](docs/project.da.md)
+- [Setup and operation](docs/setup.en.md) · [Dansk](docs/setup.da.md)
+- [Command and status protocol](docs/protocol.en.md) · [Dansk](docs/protocol.da.md)
+- [Testing and acceptance criteria](docs/testing.en.md) · [Dansk](docs/testing.da.md)
+- [AndroidRemote: pairing and access](docs/androidremote.en.md) · [Dansk](docs/androidremote.da.md)
+- [Version policy / Versionsregler](docs/versioning.md)
+- [Contributing / Bidrag](CONTRIBUTING.md)
+- [Changelog / Ændringslog](CHANGELOG.md)
+
+## What is actually implemented?
+
+| Area | Implemented in 0.0.001 | Limitation |
+|---|---|---|
+| C#/.NET 10 | Local HTTP host, validation, plugin registration, status, timeouts and bounded deduplication | No service installer or persistent queue |
+| Windows installation | Installer including .NET; Danish/English control window, start/stop, status and encrypted settings | Windows x64; unsigned development package; no automatic updates |
+| PowerPoint COM | Next, previous, go to slide, black screen, resume and status on an STA thread | Windows; exactly one existing slideshow; live acceptance pending |
+| OBS WebSocket v5 | Authentication, scene selection, start/stop recording and streaming, explicit mute state, status | Local OBS only; new connection per request; live acceptance pending |
+| Stream Deck | 12 actions, Danish/English settings, result feedback, status key and installation package | Loading verified locally; complete hardware acceptance pending |
+| AndroidRemote | Installable Android app, next/previous slide, OBS scene and status over paired HTTPS | Windows and phone need reachability on a private IPv4 network |
+| Audio, Logitech, Android Live, physical remote, Flux Keyboard | Directories, integration plans and status placeholders | No working device drivers yet |
+
+OBS audio control applies to named OBS inputs. The separate operating-system audio plugin remains planned. Stream Deck is an external client under `Plugins/StreamDeck/`; it is not reported as a hardware-connected C# plugin.
+
+## Quick start
+
+Use the Windows installer to start without a terminal or a separate .NET installation. GitHub Actions packages are development artifacts, not releases. Follow the [installation guide](docs/installation.en.html).
+
+Building from source requires .NET 10 SDK; for the priority chain, Windows, desktop PowerPoint, OBS with WebSocket v5, and Stream Deck 7.4+.
+
+```powershell
+dotnet restore ControlHub.slnx
+dotnet build ControlHub.slnx --configuration Release --no-restore
+dotnet test ControlHub.slnx --configuration Release --no-build
+node --test tests/streamdeck.test.cjs tests/inspector.test.cjs
+```
+
+Generate a random local token and start the host as described in [setup](docs/setup.en.md). Open the presentation and start its slideshow yourself. Enable OBS WebSocket and configure its password locally. Then install the Stream Deck plugin and configure the keys.
+
+## Ground rules
+
+- All plugin implementations and assets belong under `Plugins/`.
+- Control Hub must never modify presentation files. The PowerPoint adapter cannot open, save, edit or close presentation files.
+- No simulated keyboard input or focus-dependent shortcuts.
+- Commands follow explicit actions; failures and timeouts never trigger automatic replay.
+- UI text and documentation are available in Danish and English. Protocol IDs and code identifiers remain stable English names.
+- Development uses a working branch and PR to `main`. No release or tag without the owner's explicit approval.
+
+## Source layout
+
+```text
+src/ControlHub.Contracts/ shared protocol and plugin interface
+src/ControlHub.Core/ routing, validation and deduplication
+src/ControlHub.Host/ local HTTP host and explicit plugin registration
+Plugins/ all integrations and Stream Deck source assets
+tests/ C#, WebSocket, Stream Deck and host tests
+docs/ Danish and English documentation
+scripts/ project policy checks
+```
diff --git a/README.md b/README.md
index 38abc11..865a0a8 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,71 @@
-# Control Hub
-
-Source repository for Control Hub. Development is proposed through pull requests to main.
+# Control Hub · 0.0.001
+
+**Dansk** · [English](README.en.md)
+
+Control Hub er en lokal kontrolcentral til præsentationer, produktion og liveafvikling. Første prioritet er **Stream Deck → PowerPoint og OBS Studio**. Derefter følger **AndroidRemote**.
+
+Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og ærlig status, også når et program ikke er tilsluttet. Kontrol sker via programmernes grænseflader; ingen funktion afhænger af, hvilket vindue der har fokus.
+
+> **Udviklingsversion, ikke en release.** 0.0.001 indeholder en kørbar .NET 10-kerne, konkrete PowerPoint- og OBS-adaptere og et Stream Deck-plugin. Automatiske tests erstatter ikke afprøvning med fysisk Stream Deck, Office og OBS. Se [testplanen](docs/testing.da.md) og PR'ens buildresultater.
+
+## Dokumentation
+
+- [Dybdegående projektbeskrivelse](docs/project.da.md) · [English](docs/project.en.md)
+- [Installation og betjening](docs/setup.da.md) · [English](docs/setup.en.md)
+- [Windows-installationspakke: trin for trin](docs/installation.da.html) · [English](docs/installation.en.html)
+- [Kommando- og statusprotokol](docs/protocol.da.md) · [English](docs/protocol.en.md)
+- [Testplan og acceptkriterier](docs/testing.da.md) · [English](docs/testing.en.md)
+- [AndroidRemote: parring og adgang](docs/androidremote.da.md) · [English](docs/androidremote.en.md)
+- [Versionsregler / Version policy](docs/versioning.md)
+- [Bidrag / Contributing](CONTRIBUTING.md)
+- [Ændringslog / Changelog](CHANGELOG.md)
+
+## Hvad findes faktisk?
+
+| Område | Implementeret i 0.0.001 | Begrænsning |
+|---|---|---|
+| C#/.NET 10 | Lokal HTTP-host, validering, pluginregistrering, status, timeouts og begrænset dubletbeskyttelse | Ingen serviceinstallation eller vedvarende kø |
+| Windows-installation | Installer med .NET inkluderet; dansk/engelsk kontrolvindue, start/stop, status og krypterede indstillinger | Windows x64; usigneret udviklingspakke; ingen automatisk opdatering |
+| PowerPoint COM | Næste, forrige, gå til slide, sort skærm, genoptag og status via en STA-tråd | Windows; præcis ét eksisterende slideshow; endnu ikke livegodkendt |
+| OBS WebSocket v5 | Godkendelse, scenevalg, start/stop optagelse og udsendelse, eksplicit lyd fra/til, status | Kun lokal OBS; ny forbindelse pr. forespørgsel; endnu ikke livegodkendt |
+| Stream Deck | 12 handlinger, danske/engelske indstillinger, resultatfeedback, statusknap og installationspakke | Indlæsning verificeret lokalt; samlet hardwareaccept afventer |
+| AndroidRemote | Installerbar Android-app, næste/forrige slide, OBS-scene og status over parret HTTPS | Windows og telefon skal kunne nå hinanden på et privat IPv4-netværk |
+| Lyd, Logitech, Android Live, fysisk fjernkontrol, Flux Keyboard | Mapper, integrationsplaner og statuspladsholdere | Ingen fungerende enhedsdrivere endnu |
+
+OBS-lydstyring gælder navngivne OBS-lydkilder. Det separate lydplugin til operativsystemets enheder er fortsat planlagt. Stream Deck kører som en ekstern klient under `Plugins/StreamDeck/`; det optræder derfor ikke som en hardwareforbundet C#-pluginstatus.
+
+## Hurtig start
+
+Brug Windows-installationspakken for start uden terminal eller separat .NET-installation. Pakker fra GitHub Actions er udviklingsartefakter, ikke releases. Følg [installationsvejledningen](docs/installation.da.html).
+
+Ved build fra kildekode kræves .NET 10 SDK; til den prioriterede kæde Windows, PowerPoint desktop, OBS med WebSocket v5 og Stream Deck 7.4+.
+
+```powershell
+dotnet restore ControlHub.slnx
+dotnet build ControlHub.slnx --configuration Release --no-restore
+dotnet test ControlHub.slnx --configuration Release --no-build
+node --test tests/streamdeck.test.cjs tests/inspector.test.cjs
+```
+
+Opret et tilfældigt lokalt token og start værten som vist i [installationsvejledningen](docs/setup.da.md). Åbn selv præsentationen og start slideshowet. Aktivér OBS WebSocket og angiv adgangskoden lokalt. Installér derefter Stream Deck-pluginet og konfigurér knapperne.
+
+## Grundregler
+
+- Alle pluginimplementationer og pluginaktiver ligger under `Plugins/`.
+- Control Hub må aldrig ændre præsentationsfiler. Ingen åbning, gemning, indholdsredigering eller lukning af filer via PowerPoint-adapteren.
+- Ingen tastatursimulering eller fokusafhængige genveje.
+- Kommandoer sendes kun efter en konkret handling; fejl eller timeout udløser ikke automatisk gentagelse.
+- UI-tekster og dokumentation findes på dansk og engelsk. Protokol-id'er og kodeidentifikatorer er stabile engelske navne.
+- Udvikling sker på arbejdsbranch med PR mod `main`. Ingen release eller tag uden ejerens udtrykkelige godkendelse.
+
+## Kildestruktur
+
+```text
+src/ControlHub.Contracts/ fælles protokol og plugininterface
+src/ControlHub.Core/ routing, validering og dubletbeskyttelse
+src/ControlHub.Host/ lokal HTTP-host og eksplicit pluginregistrering
+Plugins/ alle integrationer og Stream Deck-kildeaktiver
+tests/ C#-, WebSocket-, Stream Deck- og hosttests
+docs/ dansk og engelsk dokumentation
+scripts/ kontrol af projektregler
+```
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..6cd41e6
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.001
diff --git a/docs/androidremote.da.md b/docs/androidremote.da.md
new file mode 100644
index 0000000..e025a75
--- /dev/null
+++ b/docs/androidremote.da.md
@@ -0,0 +1,31 @@
+# AndroidRemote i Control Hub 0.0.001
+
+[English](androidremote.en.md)
+
+AndroidRemote giver operatøren fire handlinger på telefonen. Næste og forrige slide styrer det åbne slideshow. Skift OBS-scene bruger det scenenavn, operatøren indtaster. Status viser slideposition og den aktive OBS-scene eller forklarer, hvis en integration er utilgængelig.
+
+## Installér og par
+
+1. Installér den tilhørende Windows-udviklingspakke og `ControlHub-AndroidRemote-0.0.001.apk` på en telefon med Android 8 eller nyere. Brug Windows og telefon på samme lokale netværk.
+2. Før hoststart vælger du **Tillad AndroidRemote på lokalt netværk** og computerens private IPv4-adresse på det netværk, telefonen kan nå. Start Control Hub. Telefonserveren bruger TCP-port 5188. Den lokale desktop- og Stream Deck-host bruger fortsat loopback på port 5187.
+3. Åbn **Administrér telefonadgang**. Navngiv telefonen og vælg **Læs status**, **Styr slides** og **Skift OBS-scene** efter behov. Tryk **Opret parringsbevis**. Windows viser det som *Venter* i op til to minutter.
+4. Vælg **Gem parringsfil** og overfør filen privat, for eksempel via USB. Vælg **Åbn parringsfil** på telefonen og derefter **Par telefon**. Du kan også indsætte det kopierede bevis. Beviset indeholder en hemmelighed og serverens certifikataftryk. Brug en overførsel, hvor du har kontrol over afsender og modtager. Slet filen efter brug.
+5. Start et slideshow manuelt på Windows, og vælg en eksisterende scene i OBS. Telefonen viser knapper efter de valgte rettigheder. Et ukendt udfald kræver, at operatøren kontrollerer status før næste tryk.
+
+**Fjern valgt adgang** i Windows tilbagekalder telefonens adgang. **Glem parring** på telefonen fjerner dens lokale legitimationsoplysninger. Ved hostgenstart oprettes nyt certifikat og nye parringer. Hvis certifikatkontrollen fejler efter genstart, vælg **Glem parring** og brug et nyt bevis.
+
+## Forbindelse og adgang
+
+Telefonserveren har sin egen HTTPS-lytter på én privat adresse. Telefonen kontrollerer serverens IP-navn, certifikatets gyldighed og SHA-256-aftrykket fra beviset før indløsning. Appen bruger direkte forbindelse og afviser omdirigeringer. Der oprettes ingen automatisk firewallregel. Kontrollér adgang på det private netværk, hvis telefonen ikke kan nå computeren.
+
+Beviset har 256 tilfældige bits og kan bruges én gang. Fem fejlforsøg annullerer det. Hosten reserverer højst otte ventende beviser og i alt 16 enhedspladser. Udløb måles med monoton tid. Enhedsnøglen gælder i otte timer. Hosten gemmer kun dens hash i hukommelsen. På telefonen krypteres sessionen med AES-GCM og en nøgle i Android Keystore.
+
+Rettigheder tildeles særskilt til status, slides, scener, optagelse, streaming og OBS-lyd. Den første app har knapper til de første tre kategorier. Statusrettigheden giver adgang til det samlede statusobjekt. Hosten kontrollerer rettigheder før kommandoen og efter ventekøen. En igangsat handling kan stadig afsluttes efter tilbagekaldelse. Kommandosvar knyttes til klientens id og den enkelte parring. Appen genafsender ikke en kommando efter afbrydelse.
+
+Telefonserveren begrænser en forespørgsel til 16 KiB, otte samtidige forespørgsler og 32 forbindelser. De samlede grænser pr. minut er 24 indløsningsforsøg og 240 status-/kommandokald. Ejeradministration foregår via den separate lokale host. [Protokol](protocol.da.md)
+
+## Byg og afprøv
+
+Kildekode til appen og APK-bygning ligger under `Plugins/AndroidRemote/Android/`. Kør `build.py --help` med Python 3. Brug JDK 17 eller nyere, Android SDK Platform 35 og Build Tools 36.0.0. Angiv en udviklingsnøgle uden for repositoryet. Scriptet kompilerer, pakker og verificerer APK-signaturen. Brug samme udviklingsnøgle ved lokale opdateringer. En pakke signeret med en anden nøgle kræver afinstallation og ny parring.
+
+Den automatiske Android 15-prøve installerer APK’en og bruger appens knapper gennem den rigtige TLS-server og PowerPoint-/OBS-adapterne. Kontrollerede testsessioner tæller handlinger. Forkert certifikat, parring, næste/forrige, sceneskift, status, afbrudt forbindelse, genforbindelse og tilbagekaldelse indgår. Prøven på en fysisk telefon med Windows, Office, OBS og det konkrete Wi-Fi-netværk dokumenteres særskilt. [Testvejledning](testing.da.md)
diff --git a/docs/androidremote.en.md b/docs/androidremote.en.md
new file mode 100644
index 0000000..b7e9149
--- /dev/null
+++ b/docs/androidremote.en.md
@@ -0,0 +1,31 @@
+# AndroidRemote in Control Hub 0.0.001
+
+[Dansk](androidremote.da.md)
+
+AndroidRemote gives the operator four phone controls. Next and Previous navigate the existing slideshow. Switch OBS scene uses the scene name entered by the operator. Status shows slide position and the current OBS scene or explains when an integration is unavailable.
+
+## Install and pair
+
+1. Install the matching Windows development package and `ControlHub-AndroidRemote-0.0.001.apk` on a phone running Android 8 or later. Connect Windows and the phone to the same local network.
+2. Before starting the host, select **Allow AndroidRemote on local network** and the computer’s private IPv4 address on the network reachable by the phone. Start Control Hub. The phone server uses TCP port 5188. The desktop and Stream Deck host continues to use loopback port 5187.
+3. Open **Manage phone access**. Name the phone and select **Read status**, **Control slides** and **Switch OBS scene** as needed. Click **Create invitation**. Windows lists it as *Pending* for up to two minutes.
+4. Choose **Save invitation file** and transfer the file privately, for example over USB. On the phone choose **Open invitation file** and then **Pair phone**. You can also paste the copied invitation. It contains a secret and the server certificate fingerprint. Use a transfer where you control sender and recipient. Delete the file after use.
+5. Start a slideshow manually on Windows and prepare an existing OBS scene. Controls follow the granted permissions. An unknown outcome requires checking status before another press.
+
+**Remove selected access** in Windows revokes the phone. **Forget pairing** on the phone clears its local credentials. Restarting the host creates a new certificate and requires fresh pairings. If certificate verification fails after restarting, choose **Forget pairing** and use a fresh invitation.
+
+## Connection and access
+
+The phone server has a dedicated HTTPS listener on one private address. Before redemption the phone checks the server IP identity, certificate validity and the SHA-256 fingerprint from the invitation. The app connects directly and rejects redirects. Firewall rules remain under the owner’s control. Check private network reachability if the phone cannot reach Windows.
+
+An invitation contains 256 random bits and is single-use. Five incorrect attempts cancel it. The host reserves up to eight pending invitations and 16 total device slots. Expiry uses monotonic time. The device credential lasts eight hours. The host retains only its digest in memory. The phone encrypts its session with AES-GCM using a key in Android Keystore.
+
+Separate permissions cover status, slides, scenes, recording, streaming and OBS audio. The first app provides controls for the first three categories. Status permission covers the complete status object. The host checks access on command receipt and after queueing. Already admitted operations may finish after revocation. Command responses are associated with the client ID and the individual pairing. The app does not automatically replay commands after a disconnect.
+
+The phone server limits a request to 16 KiB, eight concurrent requests and 32 connections. Aggregate limits per minute are 24 redemption attempts and 240 status/command requests. Owner administration stays on the separate local host. [Protocol](protocol.en.md)
+
+## Build and test
+
+App source and the APK build script are under `Plugins/AndroidRemote/Android/`. Run `build.py --help` with Python 3. Use JDK 17 or newer, Android SDK Platform 35 and Build Tools 36.0.0. Specify a development signing key outside the repository. The script compiles, packages and verifies the APK signature. Reuse the same development signing key for local updates. A package signed with a different key requires uninstalling and pairing again.
+
+The Android 15 automated trial installs the APK and exercises its controls through the actual TLS server and PowerPoint/OBS adapters. Controlled test sessions count actions. It covers incorrect certificates, pairing, next/previous, scene switch, status, disconnect, reconnect and revocation. A physical phone trial with Windows, Office, OBS and the actual Wi-Fi network is recorded separately. [Testing](testing.en.md)
diff --git a/docs/installation.da.html b/docs/installation.da.html
new file mode 100644
index 0000000..d819e2c
--- /dev/null
+++ b/docs/installation.da.html
@@ -0,0 +1,14 @@
+Control Hub – installation
+
+English Control Hub 0.0.001 Installationsvejledning til Windows x64 · udviklingsversion
+Stream Deck → PowerPoint og OBS er første prioritet. AndroidRemote har nu et lokalt vindue til telefonadgang. Android-appen forbindes til den valgte private netværksadresse. Installationspakken er ikke en godkendelse af praktisk afvikling.
+1. Installér Åbn ControlHub-0.0.001-win-x64-Setup.exe , og vælg Dansk. Programmet installeres for din Windows-bruger og har en almindelig afinstalleringsfunktion. .NET er inkluderet. PowerPoint desktop, OBS Studio og Stream Deck 7.4 eller nyere skal allerede være installeret. Pakken er til Windows x64; Windows 11 anbefales. Windows 10 kræver mindst build 17763, og understøttelsen af din konkrete Windows-udgave skal kontrolleres særskilt. Åbn Control Hub fra Start-menuen. Vælg Dansk eller English. Der kræves ikke et terminalvindue.
+Pakken er ikke kodesigneret og kan derfor give en Windows-advarsel om ukendt udgiver. Den installerer ingen service, ændrer ingen firewallregel og starter ikke automatisk ved login.
+2. Tilslut OBS og start Control Hub Aktivér OBS' WebSocket-server i OBS, og aflæs port og adgangskode. Brug WebSocket-adgangskoden, ikke streamingnøglen. Indtast adressen, normalt ws://127.0.0.1:4455, og adgangskoden i Control Hub. Tryk Gem indstillinger . Tryk Start Control Hub . Status viser separat, om PowerPoint og OBS svarer. Kontrollér forbindelse læser kun status.
+3. Installér Stream Deck-knapperne Tryk Installér Stream Deck-plugin i Control Hub, og gennemfør Stream Decks installationsdialog. Du kan også dobbeltklikke på den medfølgende dk.thebonden.controlhub.streamDeckPlugin. Har du allerede den manuelle udviklingsinstallation, så lad Stream Deck håndtere udskiftningen. Hvis samme version afvises, fjern kun Control Hub-pluginet i Stream Deck og installér pakken igen. Notér først knapindstillinger; ændringer kan kræve ny opsætning. Afslut og genstart Stream Deck helt, hvis gruppen mangler. Træk Status , Næste slide , Forrige slide og Skift scene fra gruppen Control Hub til en testprofil. Tryk Kopiér forbindelsesnøgle i Control Hub. Indsæt nøglen i tokenfeltet på hver Stream Deck-knap. Vælg sprog, angiv eventuelle argumenter, og tryk Gem . Tryk Test forbindelse i knappens indstillinger. Angiv OBS-scener og lydkilder med deres præcise navne.
+4. Afprøv på et testshow Start selv præcis ét PowerPoint-slideshow. Control Hub ændrer eller gemmer aldrig præsentationsfiler. Afprøv næste/forrige, sort skærm, genoptag og OBS-scenevalg, også mens et andet program har fokus. Start udsendelse er en reel livehandling; brug den kun til en aftalt testdestination eller en tilsigtet udsendelse. Installerens test starter ingen optagelse eller udsendelse.
+Administrér telefonadgang Installér den medfølgende APK på Android. Vælg Tillad AndroidRemote på lokalt netværk og computerens Wi-Fi- eller Ethernet-adresse før start. Start Control Hub og vælg Administrér telefonadgang . Indtast et navn, markér de ønskede rettigheder og vælg Opret parringsbevis . Beviset står som Venter i højst to minutter. Vælg Gem parringsfil , overfør filen privat til telefonen, vælg Åbn parringsfil i AndroidRemote og tryk Par telefon . Telefonen skal kunne nå TCP-port 5188 på den valgte adresse. Markér en række og vælg Fjern valgt adgang for at annullere den. Genstart af hosten fjerner alle beviser og enheder.
+Stop, opdatering og afinstallation Hold kontrolvinduet åbent under brug. Stop Control Hub eller lukning af vinduet stopper kun den host, vinduet har startet. PowerPoint og OBS forbliver åbne. Stop Control Hub før ændring af OBS-indstillinger og før opdatering. Afinstallér via Windows' Installerede apps. Stream Deck-pluginet fjernes separat i Stream Deck.
+Indstillinger og en tilfældig, vedvarende forbindelsesnøgle gemmes krypteret med Windows DPAPI for din bruger i %LOCALAPPDATA%\ControlHub\settings.dat. De bevares ved afinstallation. Stream Deck gemmer sin egen kopi i knappens indstillinger: del ikke profiler med nøglen, og indsæt den ikke i chat eller GitHub. Kopiering placerer nøglen på udklipsholderen; overskriv den bagefter ved at kopiere almindelig tekst.
+Hvis forbindelsen fejler Status fortæller nu, om PowerPoint blot er åbent uden diasshow, eller om flere shows er aktive. Ved manglende eller afvist OBS-adgangskode: tryk Stop Control Hub , ret adgangskoden, gem, og tryk Start Control Hub . Ved ukendt udfald af en kommando skal du kontrollere status før næste tryk. Der sker ingen automatisk gentagelse.
Port 5187 optaget: stop en tidligere terminalbaseret Control Hub, før du starter kontrolvinduets host. PowerPoint utilgængelig: start ét slideshow, luk dialoger, og kør programmerne som samme bruger og på samme rettighedsniveau. OBS utilgængelig: kontrollér lokal WebSocket-server, port og adgangskode. Indstillinger kan ikke læses: flyt settings.dat til en sikker lokal backup, og start igen. En ny nøgle skal derefter indtastes på alle knapper. Programmet overskriver ikke en ulæselig konfiguration automatisk.
+Versionen er 0.0.001. Ingen release eller tag oprettes af installeren. Hver .100-grænse og 0.1.000 kræver ejerens godkendelse.
Kildekode, tests og aktuelle begrænsninger på GitHub
diff --git a/docs/installation.en.html b/docs/installation.en.html
new file mode 100644
index 0000000..c8ce2f7
--- /dev/null
+++ b/docs/installation.en.html
@@ -0,0 +1,14 @@
+Control Hub – installation
+
+Dansk Control Hub 0.0.001 Windows x64 installation guide · development build
+Stream Deck → PowerPoint and OBS is the first priority. AndroidRemote now has a local phone access dialog. The Android app connects to the selected private network address. This installation package does not establish acceptance for live operation.
+1. Install Open ControlHub-0.0.001-win-x64-Setup.exe and select English. It installs for your Windows user and includes a standard uninstaller. .NET is included. PowerPoint desktop, OBS Studio and Stream Deck 7.4 or later must already be installed. This package targets Windows x64; Windows 11 is recommended. Windows 10 requires at least build 17763; support for your specific Windows edition must be checked separately. Open Control Hub from the Start menu. Select Dansk or English. No terminal window is needed.
+The package is not code-signed and Windows may display an unknown publisher warning. It installs no service, changes no firewall rules and does not start automatically at login.
+2. Connect OBS and start Control Hub Enable OBS' WebSocket server in OBS and check its port and password. Use the WebSocket password, not your streaming key. Enter the address, usually ws://127.0.0.1:4455, and password in Control Hub. Click Save settings . Click Start Control Hub . Status reports PowerPoint and OBS connectivity separately. Check connection only reads status.
+3. Install the Stream Deck keys Click Install Stream Deck plugin in Control Hub and complete Stream Deck's installation dialog. Alternatively, double-click the included dk.thebonden.controlhub.streamDeckPlugin. If you already have the manual development installation, let Stream Deck handle replacement. If it rejects the same version, remove only the Control Hub plugin in Stream Deck and reinstall the package. Note your key settings first; changes may require reconfiguration. Fully exit and restart Stream Deck if the group is missing. Drag Status , Next slide , Previous slide and Switch scene from the Control Hub group onto a test profile. Click Copy connection key in Control Hub. Paste it into each Stream Deck key's token field. Select a language, enter any arguments and click Save . Click Test connection in the key's settings. Enter the exact names of OBS scenes and audio inputs.
+4. Try a test show Manually start exactly one PowerPoint slideshow. Control Hub never modifies or saves presentation files. Test next/previous, black screen, resume and OBS scene selection, including while another app has focus. Start streaming is a real live operation; use it only for an agreed test destination or an intended broadcast. Installer testing does not start recording or streaming.
+Manage phone access Install the supplied APK on Android. Before starting, select Allow AndroidRemote on local network and the computer’s Wi-Fi or Ethernet address. Start Control Hub and choose Manage phone access . Enter a name, select the permissions and choose Create invitation . The invitation appears as Pending for up to two minutes. Choose Save invitation file , transfer it privately to the phone, choose Open invitation file in AndroidRemote and tap Pair phone . The phone must be able to reach TCP port 5188 on the selected address. Select a row and choose Remove selected access to cancel it. Restarting the host clears all invitations and devices.
+Stopping, updating and uninstalling Keep the control window open while using Control Hub. Stop Control Hub or closing the window stops only the host started by that window. PowerPoint and OBS remain open. Stop Control Hub before changing OBS settings and before upgrading. Uninstall via Windows Installed apps. Remove the Stream Deck plugin separately in Stream Deck.
+Settings and a random persistent connection key are encrypted with Windows DPAPI for your user in %LOCALAPPDATA%\ControlHub\settings.dat. They are preserved on uninstall. Stream Deck stores its own copy in key settings: do not share profiles containing the key or paste it into chat or GitHub. Copying puts the key on the clipboard; overwrite it afterwards by copying ordinary text.
+Troubleshooting Status now distinguishes PowerPoint being open without a slideshow from multiple active shows. For a missing or rejected OBS password: click Stop Control Hub , correct the password, save, then click Start Control Hub . If a command outcome is unknown, check status before pressing again. Commands are never automatically retried.
Port 5187 in use: stop an earlier terminal-based Control Hub before starting the control window's host. PowerPoint unavailable: start one slideshow, close dialogs, and run the apps as the same user at the same privilege level. OBS unavailable: check the local WebSocket server, port and password. Settings cannot be read: move settings.dat to a safe local backup and restart. You must then enter the new key on all buttons. The app does not automatically overwrite unreadable settings.
+The version is 0.0.001. The installer creates no release or tag. Every .100 boundary and 0.1.000 require owner approval.
Source, tests and current limitations on GitHub
diff --git a/docs/project.da.md b/docs/project.da.md
new file mode 100644
index 0000000..4a5d2c0
--- /dev/null
+++ b/docs/project.da.md
@@ -0,0 +1,102 @@
+# Projektbeskrivelse: Control Hub
+
+[English](project.en.md) · [Forside](../README.md)
+
+## Formål og brugssituation
+
+Control Hub skal samle styringen af præsentation, billedproduktion og udvalgte enheder i ét lokalt system. En operatør skal kunne fremføre slides og skifte OBS-scener fra samme Stream Deck uden at flytte fokus mellem programmerne. Systemet skal vise, om en kommando faktisk blev bekræftet, og om status kunne læses.
+
+Et typisk forløb er, at operatøren åbner præsentationen, starter slideshowet, klargør OBS og vælger en Stream Deck-profil. Et tryk på næste slide kalder PowerPoints slideshow-API. Et tryk på en OBS-scene sender en navngiven WebSocket-forespørgsel. En statusknap viser slideposition, optagelse og udsendelse. Hvis en forbindelse mangler, vises ukendt status eller en fejl; systemet skal ikke foregive, at enheden virker.
+
+0.0.001 er første gennemgående udviklingsversion. Den er et udgangspunkt for praktisk afprøvning og videre implementering, ikke en erklæring om produktionsparathed.
+
+## Prioritering og afgrænsning
+
+1. **Stream Deck, PowerPoint og OBS Studio:** få det samlede betjeningsforløb til at virke, kontrollere fejltilfælde og afprøve det i det aktive miljø.
+2. **AndroidRemote:** genbruge kommando- og statuskontrakten i en mobil fjernbetjening med parring, sikker transport og tydeligt forbindelsesniveau.
+3. **Øvrige integrationer:** lyd, Logitech, Android Live, fysisk fjernkontrol og Flux Keyboard, når de konkrete enheder, protokoller og ønskede funktioner er fastlagt.
+
+AndroidRemote og Android Live er separate integrationsspor. Der antages ikke en bestemt tredjepartsapp, et bestemt produkt-API eller en bestemt hardwaremodel ud fra navnet alene. Det samme gælder Flux Keyboard, Logitech og den fysiske fjernkontrol.
+
+Et enkelt dansk/engelsk Windows-kontrolvindue og en brugerinstallation er inkluderet: start/stop, forbindelsesstatus, kopiering af token og OBS-indstillinger. Indstillinger krypteres for Windows-brugeren med DPAPI. Hosten stopper, når kontrolvinduets forbindelse lukkes. Et fuldt visuelt afviklingspanel, brugerprofiler, makroer, samlet scene-/slideautomatik og installation som Windows-service ligger fortsat uden for første version. Ingen tidsplan eller færdiggørelsesprocent udledes af versionsnummeret.
+
+## Arkitektur
+
+```mermaid
+flowchart LR
+ SD["Stream Deck-plugin"] -->|"HTTP på loopback + token"| H["Control Hub Host"]
+ AR["AndroidRemote · Android-app"] -->|"Parret HTTPS via telefonserver"| H
+ H --> C["Validering og dispatcher"]
+ C --> P["PowerPoint-plugin · STA / COM"]
+ C --> O["OBS-plugin · WebSocket v5"]
+ C --> X["Øvrige plugins · planlagt"]
+ P --> PP["Eksisterende slideshow"]
+ O --> OBS["Lokal OBS Studio"]
+ H -->|"Status og kommandosvar"| SD
+```
+
+### Kontrakter
+
+`ControlHub.Contracts` indeholder kommando, svar, status, pluginbeskrivelse og `IHubPlugin`. Protokolversionen er uafhængig af produktversionen. Brugervendte meddelelser indeholder både `da` og `en`; klienten vælger sprog. Argumenter er JSON-objekter, og hver adapter accepterer kun sine kendte felter.
+
+### Kerne
+
+Dispatcheren validerer protokol, UUID, plugin og handling, før en adapter får kommandoen. Kommandoer serialiseres for at give en entydig rækkefølge på tværs af modtagne handlinger. De seneste 1.024 afsendte kommando-id'er huskes i hukommelsen. Samme id og identisk indhold returnerer det tidligere resultat; ændret indhold med samme id afvises.
+
+Dette er begrænset dubletbeskyttelse, ikke en vedvarende garanti for præcis én eksekvering. Historikken forsvinder ved genstart og ældre poster fjernes. Klienter må ikke genafspille gamle handlinger automatisk.
+
+### Host
+
+En ASP.NET Core-host lytter kun på `127.0.0.1:5187`. Alle API-kald kræver et bearer-token på mindst 32 tegn. Origin-bærende browserkald afvises. Indgående JSON er begrænset til 16 KiB og 16 niveauer; højst otte HTTP-forespørgsler behandles samtidig.
+
+Værten har ingen loginserver, cloudafhængighed, telemetritjeneste eller offentlig lytteadresse. Det er et lokalt proces-API, ikke en LAN-server til Android. Et fremtidigt Android-lag skal have sit eget konkrete sikkerhedsdesign.
+
+### Pluginsystem
+
+C#-plugins registreres eksplicit ved opstart og annoncerer id, navn, modenhed og handlinger. De implementerer eksekvering, status og asynkron oprydning. Værten indlæser ikke ukendte DLL-filer automatisk. Det er en bevidst afgrænsning af første version; plugins er betroet kode i samme proces, ikke isolerede sikkerhedsenheder.
+
+Alle adapterimplementeringer, enhedsspecifikke dokumenter og Stream Deck-aktiver ligger under `Plugins/`. Det fælles interface ligger i `src/`. Nye pluginimplementeringer kræver et projekt under `Plugins/`, reference i hosten, eksplicit registrering, test og dokumentation på begge sprog.
+
+## Integrationerne
+
+### PowerPoint
+
+Adapteren forbinder til den allerede kørende PowerPoint-instans via COM og kræver præcis ét slideshowvindue i den instans. Flere PowerPoint-processer eller atypiske COM-registreringer kræver praktisk afprøvning; automatisk udvælgelse på tværs af processer er ikke implementeret.
+
+COM-kald køres sekventielt på en dedikeret STA-tråd. Adapteren bruger kun slideshow-navigation og visningstilstand samt læsning af status. Den åbner, gemmer, lukker eller redigerer aldrig præsentationsfiler og afslutter ikke PowerPoint. COM-referencer frigives efter hvert kald.
+
+Næste slide følger PowerPoints egen Next-adfærd, herunder animationstrin og afslutning ved sidste slide afhængigt af præsentationens opsætning. Gå til slide bruger PowerPoints slidenummer, mens status viser positionen i det aktuelle slideshow; brugerdefinerede shows kan derfor have en anden rækkefølge. Dette skal beskrives og testes med det konkrete show.
+
+### OBS Studio
+
+Adapteren bruger OBS WebSocket v5 med challenge-response-godkendelse. Handlinger er eksplicitte: scenevalg, start/stop optagelse, start/stop udsendelse og angivelse af en lydkildes mute-tilstand. Der er ingen fokusbaserede genveje eller blind toggle af optagelse og udsendelse.
+
+Første version opretter en forbindelse pr. forespørgsel. Det forenkler genopretning efter afbrudte forbindelser, men giver ekstra håndtryk. Status læses som tre efterfølgende forespørgsler og er derfor ikke et atomisk øjebliksbillede. Hændelsesbaseret status og en vedvarende forbindelse er mulige senere forbedringer.
+
+### Stream Deck
+
+Pluginet benytter Stream Decks lokale WebSocket-API og Node 24-runtime. Det har 11 kommandoknapper og én statusknap. Indstillinger indeholder lokalt token, sprog og de argumenter, handlingen kræver. Samtidige tryk på samme knap under en igangværende forespørgsel undertrykkes; tryk efter afslutning er nye handlinger.
+
+Statusknappen opdateres normalt hvert tredje sekund. En langsom forespørgsel afsluttes før næste opdatering. Grøn bekræftelse gives kun ved et gyldigt, korreleret succes-svar. Ved fejl vises en advarsel og opfordring til at kontrollere status. Ingen automatisk gentagelse af kommandoer.
+
+Indstillingspanelets **Test forbindelse** læser status uden at udføre produktionshandlinger. Forkert token, optaget host, utilgængelig host og manglende programforbindelser vises med hver sin forklaring. Forsinkede kommandosvar må ikke opdatere en knap, hvis dens indstillinger eller profil er skiftet i mellemtiden. Elgatos officielle validator kontrollerer manifest og aktiver i CI.
+
+## Fejl, sikkerhed og databeskyttelse
+
+En timeout kan indtræffe efter, at et program har modtaget kommandoen. Derfor betyder `outcome_unknown` ikke, at handlingen aldrig skete. Operatøren skal kontrollere status. COM kan ikke tvangsafbrydes sikkert; et langsomt kald kan afsluttes efter klientens timeout.
+
+Lokalt token og OBS-adgangskode skal holdes uden for GitHub. Stream Deck gemmer token i sine lokale indstillinger; token må derfor ikke følge med eksporterede profiler eller delte konfigurationer. Værten logger ikke eksplicit kommandoindhold eller tokens. Pluginfejl sendes som kontrollerede, tosprogede meddelelser frem for rå undtagelser.
+
+Loopback og token beskytter den lokale API-grænse, men betroet plugin-kode og andre programmer med adgang til brugerens indstillinger er ikke isoleret. Før fremtidig fjernadgang skal der designes parring, TLS, adgangsrettigheder, genkaldelse af enheder og regler for genafsendelse.
+
+## Kvalitet og udviklingsforløb
+
+Automatiske tests dækker routing, validering, dubletter, timeout, adaptergrænser, OBS-håndtryk og Stream Deck-adfærd. Hosttests kontrollerer HTTP-adgang og protokolfejl. CI bygger og tester på Windows og Linux; Linux-dækning gælder den portable kerne, ikke PowerPoint COM.
+
+Fysisk accept kræver et separat forløb med den faktiske Stream Deck, Office-version, OBS-opsætning og præsentation. Den omfatter fokusskift, animationer, første/sidste slide, forbindelsesbrud og kontrol af præsentationsfilernes hash før og efter. Testresultater skal registrere miljø, trin, forventet resultat, faktisk resultat og resterende fejl.
+
+Alle ændringer går gennem PR til `main`. Versionen angives til brugeren som **0.0.001**; tekniske pakkeformater normaliserer til `0.0.1` og `0.0.1.0`. Enhver release og ethvert tag kræver ejerens godkendelse. Hver .100-grænse kræver særskilt godkendelse, og 0.1.000 kræver fuldført, accepteret scope og dokumenteret test i det aktive miljø.
+
+## AndroidRemote: første kodeetape
+
+Parring og enhedsrettigheder er nu implementeret og testet som bibliotek. Enkeltbrugsbeviser, særskilte nøgler, udløb og tilbagekaldelse beskytter adgangen. Dispatcherens kø genkontrollerer adgang før udførelse; kommando-id’er holdes adskilt pr. parring. Kontrolvinduet har nu **Administrér telefonadgang**, hvor ejeren kan oprette beviser, vælge rettigheder og tilbagekalde adgang. AndroidRemote til Android 8 og nyere forbinder til en valgfri separat HTTPS-server på den valgte netværksadresse. Appen kan gå frem og tilbage i slideshowet, vælge en navngiven OBS-scene og læse status. Se [design og afgrænsning](androidremote.da.md).
diff --git a/docs/project.en.md b/docs/project.en.md
new file mode 100644
index 0000000..6365a74
--- /dev/null
+++ b/docs/project.en.md
@@ -0,0 +1,102 @@
+# Project description: Control Hub
+
+[Dansk](project.da.md) · [Home](../README.en.md)
+
+## Purpose and operating context
+
+Control Hub brings presentation control, video production and selected devices together in one local system. An operator should be able to advance slides and switch OBS scenes from the same Stream Deck without moving focus between applications. The system must show whether a command was acknowledged and whether status could be read.
+
+A typical workflow starts with the operator opening the presentation, starting the slideshow, preparing OBS and selecting a Stream Deck profile. A next-slide key calls PowerPoint's slideshow API. An OBS scene key sends a named WebSocket request. A status key shows slide position, recording and streaming. Missing connections produce unknown status or an error; the system must not pretend a device is working.
+
+0.0.001 is the first end-to-end development version. It provides a basis for practical testing and further implementation, not a claim of production readiness.
+
+## Priorities and scope
+
+1. **Stream Deck, PowerPoint and OBS Studio:** establish the complete operating workflow, verify failure paths and test in the active environment.
+2. **AndroidRemote:** reuse the command and status contract for mobile control with pairing, secure transport and clear connection state.
+3. **Other integrations:** audio, Logitech, Android Live, physical remote and Flux Keyboard once specific devices, protocols and desired functions are established.
+
+AndroidRemote and Android Live are separate integration tracks. Their names do not establish a particular third-party app, product API or hardware model. The same applies to Flux Keyboard, Logitech and the physical remote.
+
+A small Danish/English Windows control window and per-user installer are included: start/stop, connection status, token copying and OBS settings. Settings are encrypted for the Windows user with DPAPI. The host stops when the control window's connection closes. A full visual production dashboard, user profiles, macros, combined scene/slide automation and Windows service installation remain outside the first version. The version number is not a schedule or a percentage-complete metric.
+
+## Architecture
+
+```mermaid
+flowchart LR
+ SD["Stream Deck plugin"] -->|"Loopback HTTP + token"| H["Control Hub Host"]
+ AR["AndroidRemote · Android app"] -->|"Paired HTTPS via phone server"| H
+ H --> C["Validation and dispatcher"]
+ C --> P["PowerPoint plugin · STA / COM"]
+ C --> O["OBS plugin · WebSocket v5"]
+ C --> X["Other plugins · planned"]
+ P --> PP["Existing slideshow"]
+ O --> OBS["Local OBS Studio"]
+ H -->|"Status and command results"| SD
+```
+
+### Contracts
+
+`ControlHub.Contracts` defines commands, results, status, plugin descriptors and `IHubPlugin`. The protocol version is independent of the product version. User-facing messages contain both `da` and `en`; clients select their language. Arguments are JSON objects, and each adapter accepts only its known fields.
+
+### Core
+
+The dispatcher validates the protocol, UUID, plugin and action before an adapter receives a command. Commands are serialized to establish ordering across received actions. The latest 1,024 dispatched command IDs are retained in memory. Reusing the same ID with identical content returns the earlier result; changing the content while reusing an ID is rejected.
+
+This is bounded duplicate protection, not a persistent exactly-once execution guarantee. History disappears on restart and older entries are evicted. Clients must never automatically replay old actions.
+
+### Host
+
+An ASP.NET Core host listens only on `127.0.0.1:5187`. Every API request requires a bearer token of at least 32 characters. Browser requests carrying an Origin header are rejected. Incoming JSON is limited to 16 KiB and 16 levels; at most eight HTTP requests are processed concurrently.
+
+There is no login server, cloud dependency, telemetry service or public listening address. This is a local process API, not an Android LAN server. A future Android transport needs its own concrete security design.
+
+### Plugin system
+
+C# plugins are explicitly registered at startup and advertise their ID, name, maturity and actions. They implement execution, status and asynchronous cleanup. The host does not automatically load unknown DLLs. This is an intentional first-version boundary: plugins are trusted code in the same process, not isolated security units.
+
+All adapter implementations, device-specific documents and Stream Deck assets belong under `Plugins/`. The shared interface lives under `src/`. A new implementation requires a project under `Plugins/`, a host reference, explicit registration, tests and documentation in both languages.
+
+## Integrations
+
+### PowerPoint
+
+The adapter attaches to an already running PowerPoint instance through COM and requires exactly one slideshow window in that instance. Multiple PowerPoint processes and unusual COM registrations need practical verification; selection across processes is not implemented.
+
+COM operations run sequentially on a dedicated STA thread. The adapter uses only slideshow navigation, display state and status reads. It never opens, saves, closes or edits presentation files and does not quit PowerPoint. COM references are released after each call.
+
+Next follows PowerPoint's native Next behaviour, including animation steps and end-of-show behaviour depending on presentation settings. Go-to uses PowerPoint's slide number, while status reports position in the current slideshow; custom shows can therefore have different ordering. This must be documented and tested with the actual show.
+
+### OBS Studio
+
+The adapter uses OBS WebSocket v5 with challenge-response authentication. Actions are explicit: scene selection, start/stop recording, start/stop streaming and setting an input's mute state. There are no focus-based shortcuts or blind recording/streaming toggles.
+
+The first version opens one connection per request. This simplifies recovery after disconnection but adds handshake overhead. Status uses three successive requests and is not an atomic snapshot. Event-driven status and a persistent connection are possible future improvements.
+
+### Stream Deck
+
+The plugin uses Stream Deck's local WebSocket API and Node 24 runtime. It offers 11 command keys and one status key. Settings contain the local token, language and arguments required by the action. Overlapping presses on the same key are suppressed while a request is running; presses after completion are new actions.
+
+The status key normally refreshes every three seconds. A slow request finishes before another refresh begins. Green confirmation requires a valid correlated success response. Errors show an alert and a request to check status. Commands are never automatically retried.
+
+The inspector's **Test connection** reads status without executing production actions. Incorrect tokens, busy hosts, unreachable hosts and missing application connections each have a specific explanation. Late command responses cannot update a key after its settings or profile have changed. Elgato's official validator checks the manifest and assets in CI.
+
+## Failure handling, security and data protection
+
+A timeout may occur after an application receives a command. Therefore `outcome_unknown` does not mean the action never happened. The operator must check status. COM cannot safely be forcibly cancelled; a slow call may finish after the client's timeout.
+
+The local token and OBS password must remain outside GitHub. Stream Deck stores the token in its local settings; do not include it in exported profiles or shared configurations. The host does not explicitly log command bodies or tokens. Plugin failures return controlled bilingual messages rather than raw exceptions.
+
+Loopback and token authentication protect the local API boundary, but trusted plugin code and other programs with access to the user's settings are not isolated. Future remote access must define pairing, TLS, permissions, device revocation and replay rules.
+
+## Quality and development process
+
+Automated tests cover routing, validation, duplicates, timeouts, adapter boundaries, OBS handshakes and Stream Deck behaviour. Host tests cover HTTP access and protocol errors. CI builds and tests on Windows and Linux; Linux coverage applies to the portable core, not PowerPoint COM.
+
+Physical acceptance requires a separate trial using the actual Stream Deck, Office version, OBS configuration and presentation. It covers focus changes, animations, first/last slides, disconnections and presentation file hashes before and after operation. Results must record environment, steps, expected outcome, observed outcome and remaining defects.
+
+All changes go through a PR to `main`. The user-facing version is **0.0.001**; technical package formats normalize it to `0.0.1` and `0.0.1.0`. Every release and tag requires owner approval. Each .100 boundary requires separate approval, and 0.1.000 requires completed, accepted scope and documented testing in the active environment.
+
+## AndroidRemote: first implementation stage
+
+Pairing and device permissions are now implemented and tested as a library. Single-use secrets, individual tokens, expiry and revocation control access. The dispatcher rechecks authorization after queueing; command IDs are isolated per pairing. The control window now has **Manage phone access** for creating invitations, selecting permissions and revoking access. AndroidRemote for Android 8 or later connects to an optional separate HTTPS server on the selected network address. It can advance or reverse the slideshow, select a named OBS scene and read status. See the [design and scope](androidremote.en.md).
diff --git a/docs/protocol.da.md b/docs/protocol.da.md
new file mode 100644
index 0000000..c891519
--- /dev/null
+++ b/docs/protocol.da.md
@@ -0,0 +1,107 @@
+# Kommando- og statusprotokol v1
+
+[English](protocol.en.md)
+
+Transport: lokal HTTP/JSON på `127.0.0.1:5187`. Alle kald kræver `Authorization: Bearer `. Ingen CORS, fjernadgang eller broadcast-discovery.
+
+## Endpoints
+
+| Metode og sti | Indhold |
+|---|---|
+| GET /api/v1/plugins | Registrerede C#-plugins med id, navn, modenhed og handlinger |
+| GET /api/v1/status | Protokolversion, produktversion, observationstid i UTC og pluginstatus |
+| POST /api/v1/commands | Én eksplicit kommando; returnerer et korreleret resultat |
+
+Stream Deck er en ekstern klient og står derfor ikke i C#-pluginkataloget. Planlagte plugins annoncerer tomme handlingslister og `not_implemented`.
+
+## Kommando
+
+```json
+{
+ "protocolVersion": "1",
+ "id": "73c876dd-9f55-4e02-b314-dad15a6ac386",
+ "plugin": "obs",
+ "action": "scene.switch",
+ "arguments": { "sceneName": "Camera" }
+}
+```
+
+Id skal være UUID i D-format. Feltnavne bruger camelCase. Plugin- og handlingsnavne er case-sensitive. Argumenter er altid et objekt; ukendte og gentagne argumentfelter afvises. Ukendte felter i konvolutten afvises. Grænser: 16 KiB request-body og JSON-dybde 16.
+
+| Plugin | Handling | Argumenter |
+|---|---|---|
+| powerpoint | next, previous, black, resume | {} |
+| powerpoint | goto | {"slide": 3} — positivt heltal inden for præsentationen |
+| obs | scene.switch | {"sceneName": "Camera"} |
+| obs | record.start, record.stop, stream.start, stream.stop | {} |
+| obs | input.mute | {"inputName": "Mic", "muted": true} |
+
+Navne på scener og lydkilder skal være ikke-tomme strenge på højst 256 tegn. Ingen filstier, generelle COM-kald eller vilkårlige OBS-requesttyper accepteres.
+
+## Resultat
+
+```json
+{
+ "protocolVersion": "1",
+ "id": "73c876dd-9f55-4e02-b314-dad15a6ac386",
+ "plugin": "obs",
+ "success": true,
+ "code": "ok",
+ "message": {
+ "da": "OBS bekræftede handlingen.",
+ "en": "OBS acknowledged the action."
+ },
+ "data": null
+}
+```
+
+Et læsbart kommandosvar returneres som HTTP 200, også når `success` er false. Klienten skal kontrollere version, id og success, ikke alene HTTP-status. Dårlig JSON giver 400; adgang giver 401/403; bodygrænse giver 413; kapacitetsgrænse giver 429. Transportfejl kan mangle JSON-body.
+
+Fejlkoder: `unsupported_protocol`, `invalid_command`, `unknown_plugin`, `unsupported_action`, `invalid_arguments`, `id_conflict`, `cancelled_before_dispatch`, `outcome_unknown`, `plugin_error`, `unsupported_platform`, `slideshow_unavailable`, `obs_rejected`.
+
+## Dubletter og timeout
+
+De seneste 1.024 afsendte UUID'er gemmes i hukommelsen. Identisk genafsendelse returnerer samme resultat. Ændret indhold giver id_conflict. Fingeraftrykket afhænger også af argumenternes JSON-repræsentation og rækkefølge; behold derfor den oprindelige konvolut ved et kontrolleret status-/retryforløb.
+
+Kommandoer har et samlet deadline-budget på 10 sekunder inklusive ventetid i dispatcher-køen. Annullering før dispatcheradgang giver cancelled_before_dispatch. Annullering under adapterarbejdet giver outcome_unknown. Adaptere skal respektere cancellation; allerede påbegyndte COM-kald kan fortsætte. Fejlresultater gemmes også for at undgå utilsigtet genudførelse.
+
+Historikken er hverken permanent eller en sikkerhedsgrænse mod genafspilning. Ingen automatisk kommando-retry efter timeout, genstart eller netværksfejl. OBS har sin egen requestId pr. WebSocket-forespørgsel.
+
+## Status
+
+Status indeholder `protocolVersion`, `version`, `observedAt` og `plugins`. Hvert plugin har `id`, `state`, tosproget `message` og eventuelt `data`.
+
+- PowerPoint ready-data: `position`, `slideCount`, `state` (PowerPoints numeriske visningstilstand).
+- OBS ready-data: `scene`, `recording`, `streaming`, med de relevante OBS-responseData-objekter.
+- Tilstande: `ready`, `unavailable`, `unsupported`, `not_implemented`.
+
+Hvert plugins statusopslag har et budget på 10 sekunder. Status samles sekventielt, og observedAt markerer slutningen af indsamlingen; det er ikke en atomisk måling. Manglende eller utilgængelig status må aldrig fortolkes som stoppet optagelse eller stoppet udsendelse.
+
+## Konkrete forbindelsesfejl
+
+Ved kendte fejl indeholder status og kommandosvar `data.reason`. Felterne er valgfrie og ændrer ikke protokolversion 1. Klienter skal have en generel tekst som fallback ved ukendte årsager.
+
+| Plugin | Årsager |
+|---|---|
+| PowerPoint | `powerpoint_not_found`, `no_slideshow`, `multiple_slideshows`, `powerpoint_unavailable` |
+| OBS | `connection_unavailable`, `password_missing`, `authentication_failed`, `protocol_error`, `connection_lost`, `request_rejected` |
+
+OBS-afbrydelse eller et ugyldigt svar efter påbegyndt afsendelse giver `outcome_unknown`; en udtrykkelig afvisning fra OBS giver `obs_rejected`. Ingen automatisk genafsendelse. Status forbliver `unavailable`, når årsagen kendes; det må ikke fortolkes som stoppet optagelse/udsendelse. Faste dansk/engelske tekster indeholder aldrig rå serverfejl, adgangskoder eller fejlkommentarer fra OBS. WebSocket-lukkekode 4009 identificerer afvist godkendelse ifølge den officielle OBS-protokol.
+
+## AndroidRemote-bibliotek
+
+AndroidRemote viser `ready` når telefonserveren lytter, ellers `unavailable` med `data.reason = transport_not_configured`. Telefonens TLS-server på port 5188 har POST `/phone/v1/pair`, GET `/phone/v1/status` og POST `/phone/v1/commands`. Parring tager `id` og `secret` som JSON og returnerer `device` og `token`. Status og kommandoer kræver `X-ControlHub-Device` og enhedens bearer-nøgle. Lokale ejerruter er beskrevet nedenfor. Internt bruger det protokol v1 og kan afvise med `access_denied`, før pluginhandlinger eller cachesvar frigives. Tilbagekaldelse kontrolleres igen efter kommandokøen; klientens kommando-id bevares i svaret. Se [parring og adgang](androidremote.da.md).
+
+## Lokal administration af AndroidRemote
+
+Under `/api/v1/androidremote/owner/` kræver alle kald den almindelige bearer-nøgle **og** `X-ControlHub-Owner`. Kontrolvinduet opretter 32 tilfældige bytes som en separat hexnøgle ved hver hoststart. Den gemmes ikke i indstillinger, knapper eller udklipsholder. Ved start uden en særskilt gyldig `CONTROLHUB_OWNER_KEY` registreres ejerruterne ikke. Browser-Origin afvises; ejerruter accepterer kun loopback-klienter. En legitim proces under samme Windows-bruger er ikke isoleret fra andre processer med tilsvarende adgang.
+
+| Metode og relativ sti | Resultat |
+|---|---|
+| GET (rod) | `transportReady`, `devices` og `pendingPairings`; ingen hemmeligheder |
+| POST pairings | `{"name":"Min telefon","permissions":["status.read"]}`. 201: id, bevis og udløb. Beviset kan ikke genlæses via listen. |
+| DELETE pairings/{id} | Annullerer bevis; 204 eller 404 hvis allerede væk |
+| DELETE devices/{id} | Tilbagekalder enhedens adgang; 204 eller 404 |
+| DELETE access | Fjerner alle beviser og enheder; 204 |
+
+Ugyldige/ukendte/dublerede felter eller rettigheder giver 400; kapacitetsgrænsen giver 409. Manglende almindelig nøgle giver 401; forkert ejernøgle giver 403. Ejersvar må ikke caches. Ved afbrudt oprettelse kan et bevis allerede eksistere: opdater listen og annuller det om nødvendigt. Gentag ikke automatisk. Ingen af ruterne indløser et bevis eller udfører en produktionskommando.
diff --git a/docs/protocol.en.md b/docs/protocol.en.md
new file mode 100644
index 0000000..0a531c7
--- /dev/null
+++ b/docs/protocol.en.md
@@ -0,0 +1,107 @@
+# Command and status protocol v1
+
+[Dansk](protocol.da.md)
+
+Transport: local HTTP/JSON at `127.0.0.1:5187`. Every request requires `Authorization: Bearer `. No CORS, remote access or broadcast discovery.
+
+## Endpoints
+
+| Method and path | Content |
+|---|---|
+| GET /api/v1/plugins | Registered C# plugins with ID, name, maturity and actions |
+| GET /api/v1/status | Protocol version, product version, UTC observation time and plugin status |
+| POST /api/v1/commands | One explicit command; returns a correlated result |
+
+Stream Deck is an external client and is not in the C# plugin catalog. Planned plugins advertise empty action lists and `not_implemented`.
+
+## Command
+
+```json
+{
+ "protocolVersion": "1",
+ "id": "73c876dd-9f55-4e02-b314-dad15a6ac386",
+ "plugin": "obs",
+ "action": "scene.switch",
+ "arguments": { "sceneName": "Camera" }
+}
+```
+
+IDs must be D-format UUIDs. Fields use camelCase. Plugin and action names are case-sensitive. Arguments must be objects; unknown and duplicate argument fields are rejected. Unknown envelope fields are rejected. Limits: 16 KiB request body and JSON depth 16.
+
+| Plugin | Action | Arguments |
+|---|---|---|
+| powerpoint | next, previous, black, resume | {} |
+| powerpoint | goto | {"slide": 3} — positive integer within the presentation |
+| obs | scene.switch | {"sceneName": "Camera"} |
+| obs | record.start, record.stop, stream.start, stream.stop | {} |
+| obs | input.mute | {"inputName": "Mic", "muted": true} |
+
+Scene and input names must be nonblank strings of at most 256 characters. File paths, generic COM operations and arbitrary OBS request types are not accepted.
+
+## Result
+
+```json
+{
+ "protocolVersion": "1",
+ "id": "73c876dd-9f55-4e02-b314-dad15a6ac386",
+ "plugin": "obs",
+ "success": true,
+ "code": "ok",
+ "message": {
+ "da": "OBS bekræftede handlingen.",
+ "en": "OBS acknowledged the action."
+ },
+ "data": null
+}
+```
+
+A readable command result uses HTTP 200 even when `success` is false. Clients must validate version, ID and success, not HTTP status alone. Invalid JSON produces 400; access failures 401/403; body limit 413; capacity limit 429. Transport errors may not have a JSON body.
+
+Error codes: `unsupported_protocol`, `invalid_command`, `unknown_plugin`, `unsupported_action`, `invalid_arguments`, `id_conflict`, `cancelled_before_dispatch`, `outcome_unknown`, `plugin_error`, `unsupported_platform`, `slideshow_unavailable`, `obs_rejected`.
+
+## Duplicates and timeouts
+
+The latest 1,024 dispatched UUIDs are retained in memory. An identical resend returns the same result. Changed content produces id_conflict. Fingerprints also depend on argument JSON representation and ordering; preserve the original envelope for any controlled reconciliation/retry workflow.
+
+Commands have a total deadline budget of 10 seconds including dispatcher queue time. Cancellation before acquiring dispatcher access produces cancelled_before_dispatch. Cancellation during adapter work produces outcome_unknown. Adapters must honour cancellation; already running COM calls may continue. Failure results are cached too, to prevent unintended re-execution.
+
+History is neither persistent nor an anti-replay security boundary. Do not automatically retry commands after timeout, restart or network failure. OBS uses a separate requestId for each WebSocket request.
+
+## Status
+
+Status contains `protocolVersion`, `version`, `observedAt` and `plugins`. Each plugin has `id`, `state`, a bilingual `message` and optional `data`.
+
+- PowerPoint ready data: `position`, `slideCount`, `state` (PowerPoint's numeric display state).
+- OBS ready data: `scene`, `recording`, `streaming`, containing the relevant OBS responseData objects.
+- States: `ready`, `unavailable`, `unsupported`, `not_implemented`.
+
+Each plugin status lookup has a 10-second budget. Status is collected sequentially and observedAt marks the end of collection; it is not an atomic snapshot. Missing or unavailable status must never be interpreted as recording or streaming being stopped.
+
+## Specific connection failures
+
+Known failures include `data.reason` in status and command results. These optional fields do not change protocol version 1. Clients must use a general fallback for unknown reasons.
+
+| Plugin | Reasons |
+|---|---|
+| PowerPoint | `powerpoint_not_found`, `no_slideshow`, `multiple_slideshows`, `powerpoint_unavailable` |
+| OBS | `connection_unavailable`, `password_missing`, `authentication_failed`, `protocol_error`, `connection_lost`, `request_rejected` |
+
+An OBS disconnect or invalid reply after starting request transmission produces `outcome_unknown`; an explicit OBS rejection produces `obs_rejected`. No automatic retry. Status remains `unavailable` when a cause is known; it must not imply recording/streaming is stopped. Fixed Danish/English messages never include raw server errors, passwords or OBS error comments. WebSocket close code 4009 identifies authentication failure according to the official OBS protocol.
+
+## AndroidRemote library
+
+AndroidRemote reports `ready` while the phone server is listening, otherwise `unavailable` with `data.reason = transport_not_configured`. The phone TLS server on port 5188 provides POST `/phone/v1/pair`, GET `/phone/v1/status` and POST `/phone/v1/commands`. Pairing takes `id` and `secret` as JSON and returns `device` and `token`. Status and commands require `X-ControlHub-Device` and the device bearer token. Local owner routes are described below. Internally it uses protocol v1 and may return `access_denied` before allowing plugin actions or cached results. Revocation is rechecked after the command queue; responses preserve the client command ID. See [pairing and access](androidremote.en.md).
+
+## Local AndroidRemote administration
+
+All routes under `/api/v1/androidremote/owner/` require the normal bearer key **and** `X-ControlHub-Owner`. The control window generates a separate 32-byte random hex key for each host launch. It is not saved in settings, keys or the clipboard. Without a distinct valid `CONTROLHUB_OWNER_KEY`, the host does not register owner routes. Browser Origin is rejected; owner routes accept loopback clients only. Processes running with equivalent access under the same Windows user are not isolated from one another.
+
+| Method and relative path | Result |
+|---|---|
+| GET (root) | `transportReady`, `devices` and `pendingPairings`; no secrets |
+| POST pairings | `{"name":"My phone","permissions":["status.read"]}`. 201: ID, secret and expiry. The list cannot retrieve the secret. |
+| DELETE pairings/{id} | Cancel invitation; 204 or 404 if already gone |
+| DELETE devices/{id} | Revoke device access; 204 or 404 |
+| DELETE access | Remove all invitations and devices; 204 |
+
+Invalid, unknown or duplicate fields/permissions return 400; capacity returns 409. Missing the regular key returns 401; an incorrect owner key returns 403. Owner responses must not be cached. After an interrupted creation request an invitation may already exist: refresh and cancel it if needed. Do not automatically retry. None of these routes redeem invitations or execute production commands.
diff --git a/docs/references.md b/docs/references.md
new file mode 100644
index 0000000..1672fe5
--- /dev/null
+++ b/docs/references.md
@@ -0,0 +1,19 @@
+# Tekniske kilder / Technical references
+
+Disse officielle kilder ligger til grund for integrationsvalgene. / These official sources inform the integration choices.
+
+- [.NET SDK selection / SDK-valg](https://learn.microsoft.com/en-us/dotnet/core/tools/global-json)
+- [PowerPoint SlideShowView.Next](https://learn.microsoft.com/en-us/office/vba/api/powerpoint.slideshowview.next)
+- [OBS WebSocket v5 protocol / protokol](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md)
+- [Stream Deck manifest](https://docs.elgato.com/streamdeck/sdk/references/manifest/)
+- [Stream Deck WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/plugin/)
+- [Stream Deck runtimes](https://docs.elgato.com/streamdeck/sdk/introduction/plugin-environment/)
+- [Stream Deck distribution / distribution](https://docs.elgato.com/streamdeck/sdk/introduction/distribution/)
+- [Stream Deck installation packaging / installationspakning](https://docs.elgato.com/streamdeck/cli/commands/pack/)
+- [.NET self-contained deployment / inkluderet runtime](https://learn.microsoft.com/en-us/dotnet/core/deploying/)
+- [Windows DPAPI / krypteret konfiguration](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.protecteddata)
+- [Inno Setup per-user installation / brugerinstallation](https://jrsoftware.org/ishelp/topic_setup_privilegesrequired.htm)
+
+Henvisninger beskriver API'er; de er ikke bevis for lokal hardwaretest. / References describe APIs; they are not evidence of local hardware testing.
+
+- [.NET fixed-time hash comparison / sammenligning af hash](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptographicoperations.fixedtimeequals?view=net-10.0)
diff --git a/docs/setup.da.md b/docs/setup.da.md
new file mode 100644
index 0000000..d9c636a
--- /dev/null
+++ b/docs/setup.da.md
@@ -0,0 +1,95 @@
+# Installation og betjening
+
+[English](setup.en.md) · [Forside](../README.md)
+
+## Forudsætninger
+
+For den færdigbyggede Windows x64-pakke: følg [installationsvejledningen](installation.da.html). Den inkluderer .NET og et kontrolvindue; SDK og Node er kun nødvendige for udvikling og tests. Installationsfilerne er udviklingsartefakter, ikke en release.
+
+- Windows 10/11 til PowerPoint COM; .NET 10 SDK til build.
+- PowerPoint desktop installeret. PowerPoint i browseren understøttes ikke.
+- OBS Studio med WebSocket v5 aktiveret. OBS og Control Hub kører på samme maskine.
+- Stream Deck 7.4 eller nyere, som indeholder Node 24-runtime til pluginet.
+- Node 24 til JavaScript-tests. Ingen npm-afhængigheder er nødvendige.
+- PowerPoint, Stream Deck og Control Hub bør køre som samme Windows-bruger og på samme rettighedsniveau.
+
+## Byg og test
+
+Kør fra repositoryets rod:
+
+```powershell
+dotnet restore ControlHub.slnx
+dotnet build ControlHub.slnx -c Release --no-restore
+dotnet test ControlHub.slnx -c Release --no-build
+node --test tests/streamdeck.test.cjs tests/inspector.test.cjs
+node scripts/check-policy.cjs
+```
+
+`node tests/host-smoke.cjs` starter en kortvarig testhost på en separat, automatisk valgt loopback-port. Din normale host kan fortsætte. Den bruger et tilfældigt testtoken, kontakter ikke produktions-OBS og sender ingen slideshow-kommandoer, men læser PowerPoint-status.
+
+## Lokal konfiguration
+
+I PowerShell 7 kan et token dannes uden at gemme det i en fil:
+
+```powershell
+$env:CONTROLHUB_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
+$env:CONTROLHUB_OBS_URL = 'ws://127.0.0.1:4455'
+$secret = Read-Host 'OBS WebSocket-adgangskode' -AsSecureString
+$env:CONTROLHUB_OBS_PASSWORD = [System.Net.NetworkCredential]::new('', $secret).Password
+dotnet run --project src/ControlHub.Host --configuration Release --no-build
+```
+
+OBS WebSocket aktiveres under OBS' indstillinger for WebSocket-serveren. Kopiér det konfigurerede portnummer til URL'en. Angiv den adgangskode, der er indstillet i OBS; brug ikke din streamingnøgle. Værten accepterer kun en lokal `ws://`-adresse uden sti eller brugeroplysninger.
+
+API-adressen er fast `http://127.0.0.1:5187`. Hostens token skal kopieres privat til hver Stream Deck-knap. For at hente det kan du bruge `$env:CONTROLHUB_TOKEN` i det samme terminalvindue før start; del aldrig outputtet. Tokenet er ikke permanent gemt af denne vejledning. Ved nyt token skal knappernes indstillinger opdateres. Adgangskoder og tokens må ikke lægges i repositoryet.
+
+## Installér Stream Deck-kildepluginet
+
+1. Afslut Stream Deck.
+2. Kopiér hele mappen `Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin` til `%APPDATA%\Elgato\StreamDeck\Plugins\`. Bevar mappenavnet og alle filer.
+3. Start Stream Deck igen. Gruppen **Control Hub** skal nu være synlig.
+4. Træk **Næste slide / Next slide**, **Forrige slide / Previous slide**, **Skift scene / Switch scene** og **Status / Status** til din profil.
+5. Vælg Dansk eller English, indsæt det lokale token, udfyld eventuelle argumenter og tryk Gem/Save på hver knap.
+6. Tryk **Test forbindelse**. Testen bruger tokenet i feltet uden at gemme det og læser kun status. Den skifter ikke slide, scene, optagelse eller udsendelse. Den viser separat, om Control Hub, PowerPoint og OBS svarer. Gem tokenet med **Gem**, når opsætningen er korrekt.
+7. OBS-scener og lydkilder skal angives med deres præcise navne. Gå til slide kræver et positivt heltal. Lyd fra/til angiver ønsket tilstand; det er ikke en blind toggle.
+
+Ovenstående er den manuelle udviklingsinstallation fra kildekode. Alternativt installeres den byggede `.streamDeckPlugin`-fil med dobbeltklik. Windows-installeren indeholder både denne pakke og kontrolvinduet. Ingen Marketplace-udgivelse, release eller tag er oprettet.
+
+## Byg installationsfiler (Windows)
+
+Installér Inno Setup 6.7.3, .NET 10 SDK og Node 24 med npm. Kør:
+
+```powershell
+./scripts/package-windows.ps1 -IsccPath 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' -OutputDirectory "$PWD\artifacts\windows"
+./scripts/verify-package.ps1 -PackageDirectory "$PWD\artifacts\windows"
+```
+
+Outputmappen skal være ny for at undgå gamle filer. `files/` indeholder Windows-setup, Stream Deck-pakke og SHA-256-kontrolsummer. `payload/` indeholder de pakkede programmer. Verifikation afprøver krypterede indstillinger, ugyldige adresser, den pakkede host, optaget port og stop; den sender ingen slideshow- eller OBS-handlinger. GitHub Actions bygger og gemmer Windows-pakken som en midlertidig artefakt efter tests. Der oprettes ingen release/tag.
+
+## Klargør PowerPoint og OBS
+
+Åbn selv præsentationen, og start præcis ét slideshow i den tilknyttede PowerPoint-instans. Control Hub åbner eller gemmer ikke filer. Kontrollér statusknappen, før du trykker på navigation. Prøv først på et kontrolleret testshow.
+
+Start OBS, aktivér WebSocket-serveren, og kontrollér navnene på dine scener og lydkilder. Start udsendelse sender en reel StartStream-anmodning med OBS' eksisterende konfiguration; brug kun knappen, når du faktisk vil sende live. Optagelse og udsendelse har separate start- og stopknapper.
+
+## Feedback og fejlfinding
+
+| Observation | Betydning og handling |
+|---|---|
+| Grøn bekræftelse | Programmet har bekræftet kommandoen. Det er ikke en videobekræftelse af det synlige resultat. |
+| Tjek status / Check status | Kommandoen fejlede, eller udfaldet er ukendt. Kontrollér programmet og status før nyt tryk. |
+| PPT ? | PowerPoint er utilgængelig, eller der findes ikke præcis ét slideshow. |
+| OPT/REC ? eller LIVE ? | OBS-status kunne ikke læses. Kontrollér server, port og adgangskode. |
+| 401 | Token mangler eller er forkert. |
+| 403 | Kaldet har en browser-Origin. Brug Stream Deck-pluginets Node-klient eller en direkte API-klient. |
+| 429 | Hosten har otte aktive forespørgsler. Vent, og kontrollér status. Gentag ikke en handling ukritisk. |
+| Pluginet mangler | Kontrollér mappe, manifest, Stream Deck-version og genstart. |
+| COM optaget/afvist | Luk dialoger i PowerPoint, kontrollér brugersession og rettighedsniveau. En ny kommando kræver operatørens vurdering. |
+
+Status opdateres cirka hvert tredje sekund, når forbindelserne svarer hurtigt. Ingen statusopdatering eller fejl udløser en ny produktionskommando automatisk.
+
+## Stop
+
+Stop Control Hub med Ctrl+C i dens terminal. Pluginet må ikke afslutte PowerPoint eller OBS. Fjern eventuelt det lokale token fra Stream Deck-indstillinger, før en profil eksporteres.
+
+Ved udvikling kan `CONTROLHUB_PORT` vælge en anden lokal port; `0` lader operativsystemet vælge. Adressen er altid loopback. Kontrolvinduet fastsætter fortsat port 5187, som Stream Deck også bruger.
diff --git a/docs/setup.en.md b/docs/setup.en.md
new file mode 100644
index 0000000..010d874
--- /dev/null
+++ b/docs/setup.en.md
@@ -0,0 +1,95 @@
+# Setup and operation
+
+[Dansk](setup.da.md) · [Home](../README.en.md)
+
+## Prerequisites
+
+For the prebuilt Windows x64 package, follow the [installation guide](installation.en.html). It includes .NET and a control window; the SDK and Node are only needed for development and tests. Installation files are development artifacts, not a release.
+
+- Windows 10/11 for PowerPoint COM; .NET 10 SDK for building.
+- Installed desktop PowerPoint. Browser-based PowerPoint is not supported.
+- OBS Studio with WebSocket v5 enabled. OBS and Control Hub run on the same machine.
+- Stream Deck 7.4 or later, including the plugin's Node 24 runtime.
+- Node 24 for JavaScript tests. No npm dependencies are required.
+- Run PowerPoint, Stream Deck and Control Hub as the same Windows user at the same privilege level.
+
+## Build and test
+
+From the repository root:
+
+```powershell
+dotnet restore ControlHub.slnx
+dotnet build ControlHub.slnx -c Release --no-restore
+dotnet test ControlHub.slnx -c Release --no-build
+node --test tests/streamdeck.test.cjs tests/inspector.test.cjs
+node scripts/check-policy.cjs
+```
+
+`node tests/host-smoke.cjs` starts a temporary test host on a separate, automatically selected loopback port. Your normal host can keep running. It uses a random test token, does not contact production OBS and sends no slideshow commands, but reads PowerPoint status.
+
+## Local configuration
+
+PowerShell 7 can generate a token without saving it to a file:
+
+```powershell
+$env:CONTROLHUB_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
+$env:CONTROLHUB_OBS_URL = 'ws://127.0.0.1:4455'
+$secret = Read-Host 'OBS WebSocket password' -AsSecureString
+$env:CONTROLHUB_OBS_PASSWORD = [System.Net.NetworkCredential]::new('', $secret).Password
+dotnet run --project src/ControlHub.Host --configuration Release --no-build
+```
+
+Enable the OBS WebSocket server in OBS' WebSocket server settings. Copy the configured port into the URL. Supply the password configured in OBS, not your streaming key. The host accepts only a local `ws://` endpoint without a path or user information.
+
+The API address is fixed at `http://127.0.0.1:5187`. Privately copy the host token to each Stream Deck key. You can retrieve it with `$env:CONTROLHUB_TOKEN` in the same terminal before starting the host; never share the output. This guide does not persist the token. When it changes, update the keys. Do not commit passwords or tokens.
+
+## Install the Stream Deck source plugin
+
+1. Quit Stream Deck.
+2. Copy the entire `Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin` folder into `%APPDATA%\Elgato\StreamDeck\Plugins\`. Preserve its folder name and all files.
+3. Restart Stream Deck. The **Control Hub** category should appear.
+4. Drag **Næste slide / Next slide**, **Forrige slide / Previous slide**, **Skift scene / Switch scene** and **Status / Status** onto your profile.
+5. Choose Dansk or English, enter the local token and any required arguments, and click Gem/Save for every key.
+6. Click **Test connection**. It uses the entered token without saving it and only reads status. It does not change slides, scenes, recording or streaming. It reports Control Hub, PowerPoint and OBS separately. Click **Save** to retain the token once configured.
+7. Enter exact OBS scene and input names. Go-to requires a positive slide number. Mute specifies a desired state rather than blindly toggling.
+
+The above is the manual development installation from source. Alternatively, double-click the built `.streamDeckPlugin` file. The Windows installer includes this package and the control window. No Marketplace publication, release or tag has been created.
+
+## Build installation files (Windows)
+
+Install Inno Setup 6.7.3, .NET 10 SDK and Node 24 with npm. Run:
+
+```powershell
+./scripts/package-windows.ps1 -IsccPath 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' -OutputDirectory "$PWD\artifacts\windows"
+./scripts/verify-package.ps1 -PackageDirectory "$PWD\artifacts\windows"
+```
+
+The output directory must be new to avoid stale files. `files/` contains Windows setup, the Stream Deck package and SHA-256 checksums. `payload/` contains the packaged applications. Verification tests encrypted settings, invalid addresses, the packaged host, occupied ports and shutdown; it sends no slideshow or OBS actions. GitHub Actions builds and stores the Windows package as a temporary artifact after tests. No release/tag is created.
+
+## Prepare PowerPoint and OBS
+
+Open the presentation yourself and start exactly one slideshow in the attached PowerPoint instance. Control Hub does not open or save files. Check the status key before navigating. Begin with a controlled test show.
+
+Start OBS, enable its WebSocket server and verify scene and input names. Start streaming sends a real StartStream request using the existing OBS configuration; use it only when you intend to broadcast. Recording and streaming have separate start and stop keys.
+
+## Feedback and troubleshooting
+
+| Observation | Meaning and action |
+|---|---|
+| Green confirmation | The application acknowledged the command. This is not visual verification of its on-screen result. |
+| Tjek status / Check status | The command failed or its outcome is unknown. Check the application and status before pressing again. |
+| PPT ? | PowerPoint is unavailable or there is not exactly one slideshow. |
+| OPT/REC ? or LIVE ? | OBS status could not be read. Check server, port and password. |
+| 401 | Missing or incorrect token. |
+| 403 | The request contains a browser Origin. Use the Stream Deck Node client or a direct API client. |
+| 429 | Eight requests are active. Wait and check status. Do not blindly replay an action. |
+| Missing plugin | Check the folder, manifest and Stream Deck version, then restart. |
+| COM busy/rejected | Close PowerPoint dialogs and check the user session and privilege level. Another command requires operator judgment. |
+
+Status normally refreshes approximately every three seconds when connections respond promptly. Status refreshes and errors never automatically issue another production command.
+
+## Stop
+
+Stop Control Hub with Ctrl+C in its terminal. The plugin must not quit PowerPoint or OBS. Remove the local token from Stream Deck settings before exporting a profile.
+
+For development, `CONTROLHUB_PORT` selects another local port; `0` lets the operating system choose. The address is always loopback. The control window explicitly sets port 5187, also used by Stream Deck.
diff --git a/docs/testing.da.md b/docs/testing.da.md
new file mode 100644
index 0000000..be54af9
--- /dev/null
+++ b/docs/testing.da.md
@@ -0,0 +1,71 @@
+# Testplan og accept
+
+[English](testing.en.md)
+
+## Automatiske kontroller
+
+- Windows-pakketest: inkluderet runtime, DPAPI-konfiguration, ødelagt konfiguration, lokal adressevalidering, start af den pakkede host, autentificeret status, optaget port og stop via lukket inputforbindelse. Kør `scripts/verify-package.ps1` efter pakning; den afprøver ikke fysisk styring.
+
+- Release-build af alle C#-projekter med advarsler som fejl.
+- Routing, UUID, protokolversion, ukendte handlinger og ugyldige argumenter.
+- Parallelle dubletter udføres én gang inden for cachevinduet; konflikt-id'er afvises.
+- Timeout og annullering skelner mellem ikke afsendt og ukendt udfald.
+- PowerPoint-adapterens kald afprøves mod en falsk session. Åbning, gemning, redigering og lukning er ikke handlinger.
+- OBS testes mod en lokal simuleret WebSocket-server: håndtryk, password challenge, fragmenterede svar, mellemliggende events, requestfejl og forkert korrelation.
+- Elgatos officielle CLI 1.10.3 validerer pluginmanifest og aktiver, herunder hovedikonets PNG-format. Validering er ikke en fysisk installationstest.
+- Forbindelsestesten kontrolleres for kun at sende GET-status og aldrig gemme eller sende tokenet tilbage i et svar. UI-tests dækker korrelation, sprog, timeout og ændring af token under et kald.
+- Forsinket succes eller fejl må ikke vises på en nykonfigureret knap eller en genbrugt kontekst.
+- Stream Deck testes med simuleret HTTP: knaptryk, argumentmapping, overlap, fejlfeedback, manglende token og status.
+- Host-smoketest: adgang, Origin-afvisning, ugyldig JSON, version, handlinger og utilgængelige integrationer.
+- Kildekoderegler: ingen præsentationsfiler, ingen kendte filskrivnings- eller fokusoperationer i PowerPoint-adapteren.
+
+CI kører på Windows og Linux. Testene ændrer ikke præsentationsfiler og sender ikke produktionskommandoer til brugerens OBS. En grøn CI-kørsel beviser ikke, at COM, Stream Deck-installation og den konkrete hardware er afprøvet.
+
+## Fysisk accept — endnu ikke gennemført
+
+| Trin | Forventet resultat |
+|---|---|
+| Installér kildepluginet i Stream Deck | Alle 12 handlinger vises; begge sprog kan vælges |
+| Start host med forkert/manglende token i knappen | Ingen handling; tydelig fejl |
+| Start ét slideshow og en testopsætning i OBS | Status viser korrekt position og outputtilstand |
+| Flyt fokus til et andet program | Næste/forrige og OBS-scenevalg virker stadig |
+| Næste/forrige med animationer | PowerPoints native adfærd, én handling pr. bevidst tryk |
+| Gå til gyldig/ugyldig slide | Gyldig navigation; ugyldig afvises uden ændring |
+| Sort skærm og genoptag | Kun slideshowvisning ændres |
+| Første/sidste slide og brugerdefineret show | Adfærd dokumenteret og accepteret |
+| To slideshowvinduer | Adapteren afviser tvetydig styring |
+| Forkert OBS-adgangskode eller scenenavn | Ingen falsk succes; brugbar fejlfeedback |
+| Start/stop testoptagelse og mute/unmute | OBS bekræfter den ønskede tilstand |
+| Start/stop udsendelse til godkendt testdestination | Kun ved eksplicit, aftalt live-test |
+| Luk/genstart OBS eller PowerPoint | Status bliver utilgængelig og kan genfindes; ingen automatisk genafspilning |
+| Afbryd under kommando | Ukendt udfald behandles ved statuskontrol |
+| Sammenlign præsentationsfilens SHA-256 før/efter | Identisk filindhold |
+| Stop host | PowerPoint og OBS forbliver åbne |
+
+Beregn filhash med `Get-FileHash -Algorithm SHA256 -LiteralPath ''` før og efter. Testen må ikke gemme præsentationen eller bruge redigering som del af testen. Brug ikke produktionsudsendelser til en uvarslet test.
+
+## Registrering
+
+For hvert testforløb registreres dato, Windows/Office/OBS/Stream Deck-versioner, hardwaremodel, plugincommit, testtrin, forventet og faktisk resultat, filhash og operatørens godkendelse. Del ikke tokens, OBS-password eller streamingnøgler.
+
+0.0.001 kan først betegnes hardwareverificeret, når denne protokol er gennemført og resultaterne er vedlagt. 0.1.000 kræver derudover ejerens godkendelse af det fulde scope og dokumentation fra det aktive miljø.
+
+## Lokal integrationsstatus — opdateret 1. november 2026
+
+Den 31. oktober blev den rettede forbindelsesdialog afprøvet i det installerede Stream Deck-plugin: Control Hub, PowerPoint og OBS svarede. Statusknappen viste slide 1 og stoppet optagelse/udsendelse.
+
+En praktisk prøve sendte simulerede knaptryk gennem pluginets produktionskode til den åbne lokale Control Hub 0.0.001-testudgave, PowerPoint COM og OBS 33.0.1. Næste/forrige, gå til slide, ugyldig slide, sort skærm/genoptag og OBS-scenevalg bestod. Slide 1 og den oprindelige scene blev gendannet. Præsentationsfilens SHA-256 var uændret. Ingen optagelse eller udsendelse blev startet. Prøven brugte det allerede åbne kontrolvindue fra package-001-b; installationstestene af den nye pakke er separate.
+
+Ejeren bekræftede derefter, at den fysiske Næste-knap på Stream Deck XL skifter slide. Den efterfølgende COM-aflæsning fandt ikke præcis ét aktivt slideshow, så det konkrete slidenummer er ikke uafhængigt verificeret. Profile 2 har Status, Næste, Forrige, OBS SORT og OBS PPT. Fysiske tryk på de øvrige knapper samt optagelse, udsendelse, mute, animationer og fuld hardwareaccept er endnu ikke bekræftet.
+
+Den 1. november består 51 C#-tests og 27 JavaScript-tests efter tilføjelse af konkrete forbindelsesårsager. Tests dækker manglende og afvist OBS-adgangskode, lukket port, ugyldigt håndtryk, afbrydelse efter afsendelse, PowerPoint-fejlårsager og sikker tosproget statusvisning. Den simulerede OBS-server bruges til fejlprøver; brugerens serverindstillinger ændres ikke af testene.
+
+## AndroidRemote-kodeetape — 1. november 2026
+
+Efter AndroidRemote-biblioteket består 89 C#-tests og 27 JavaScript-tests. De 38 nye testtilfælde omfatter samtidig enkeltbrugsparring, udløb, forkert nøgle, rettigheder, enhedsgrænser, tilbagekaldelse under kø/statuslæsning, adskilt dublethistorik og ukendt udfald uden automatisk replay. Host-smoketesten består på en separat lokal port, mens den normale Control Hub kører. Build: nul advarsler/fejl. Dette er bibliotekstest med simulerede enheder, ikke Android-hardwaretest.
+
+## Telefonvindue — 2. november 2026
+
+Android-APK'en blev efterfølgende installeret på en Android 15-testemulator. Testen afviste et ændret certifikataftryk og brugte derefter samme bevis med det rigtige aftryk. Næste og Forrige gav to navigationer i alt. Ét tryk på sceneknappen gav ét OBS-skift. Efter netværksafbrydelse kom status tilbage med den oprindelige slide og valgte scene. Tællerne steg ikke ved genforbindelse eller tilbagekaldelse. Telefonen genlæste sin krypterede session mellem prøveforløbene. PowerPoint- og OBS-adapterne brugte kontrollerede testsessioner.
+
+Servertesten opretter, viser og annullerer testbeviser og kontrollerer kapacitetsgrænsen. Manglende ejernøgle, kun Stream Deck-nøglen, Origin-kald og ugyldige felter afvises. Beviser og nøgler er ikke i oversigten. Den pakkede desktopklient har en separat test af opret/læs/annuller. Det faktiske Windows-vindue blev kontrolleret visuelt på begge sprog med simulerede enheder, inklusive dansk oprettelse af et bevis med kun læseadgang. Der blev ikke anvendt en telefon.
diff --git a/docs/testing.en.md b/docs/testing.en.md
new file mode 100644
index 0000000..c6152cd
--- /dev/null
+++ b/docs/testing.en.md
@@ -0,0 +1,71 @@
+# Test plan and acceptance
+
+[Dansk](testing.da.md)
+
+## Automated checks
+
+- Windows package checks: included runtime, DPAPI configuration, corrupt configuration, local address validation, packaged host startup, authenticated status, occupied ports and shutdown through a closed input connection. Run `scripts/verify-package.ps1` after packaging; this does not test physical control.
+
+- Release build of all C# projects with warnings treated as errors.
+- Routing, UUIDs, protocol versions, unknown actions and invalid arguments.
+- Concurrent duplicate commands execute once within the cache window; conflicting IDs are rejected.
+- Timeouts and cancellation distinguish not dispatched from unknown outcome.
+- PowerPoint adapter calls are tested against a fake session. Opening, saving, editing and closing are not actions.
+- OBS uses a local simulated WebSocket server: handshake, password challenge, fragmented replies, intervening events, request failures and mismatched correlation.
+- Elgato's official CLI 1.10.3 validates the plugin manifest and assets, including the main icon's PNG format. Validation is not a physical installation test.
+- The connection check is verified to send only a status GET and never save or echo the token in its reply. UI tests cover correlation, language, timeout and editing the token during a request.
+- Late success or failure must not appear on a reconfigured key or reused context.
+- Stream Deck uses simulated HTTP: key presses, argument mapping, overlap, failure feedback, missing token and status.
+- Host smoke test: authentication, Origin rejection, malformed JSON, version, actions and unavailable integrations.
+- Source policy: no presentation files and no known file-writing or focus operations in the PowerPoint adapter.
+
+CI runs on Windows and Linux. Tests do not modify presentation files or send production commands to the user's OBS. Green CI does not prove COM, Stream Deck installation or specific hardware has been tested.
+
+## Physical acceptance — not yet completed
+
+| Step | Expected outcome |
+|---|---|
+| Install source plugin in Stream Deck | All 12 actions appear; both languages selectable |
+| Configure a missing/incorrect token | No action; clear error |
+| Start one slideshow and a test OBS setup | Correct position and output status |
+| Move focus to another application | Navigation and OBS scene selection still work |
+| Next/previous with animations | Native PowerPoint behaviour; one action per intentional press |
+| Go to valid/invalid slide | Valid navigation; invalid request rejected without a change |
+| Black screen and resume | Only slideshow display state changes |
+| First/last slide and custom show | Behaviour documented and accepted |
+| Two slideshow windows | Ambiguous control rejected |
+| Wrong OBS password or scene name | No false success; useful failure feedback |
+| Start/stop test recording and mute/unmute | OBS confirms the desired state |
+| Start/stop streaming to an approved test destination | Only during an explicitly agreed live test |
+| Close/restart OBS or PowerPoint | Status becomes unavailable and recovers; no automatic replay |
+| Disconnect during a command | Unknown outcome reconciled using status |
+| Compare presentation SHA-256 before/after | Identical file content |
+| Stop host | PowerPoint and OBS stay open |
+
+Use `Get-FileHash -Algorithm SHA256 -LiteralPath ''` before and after. The test must not save the presentation or include editing. Do not use production broadcasts for an unannounced test.
+
+## Recording results
+
+Record date, Windows/Office/OBS/Stream Deck versions, hardware model, plugin commit, steps, expected and observed outcomes, file hashes and operator approval. Never share tokens, OBS passwords or streaming keys.
+
+0.0.001 may only be called hardware-verified after this procedure is completed and its evidence attached. 0.1.000 additionally requires owner approval of the full scope and evidence from the active environment.
+
+## Local integration status — updated 1 November 2026
+
+On 31 October the corrected connection dialog was exercised in the installed Stream Deck plugin: Control Hub, PowerPoint and OBS responded. The status key showed slide 1 with recording/streaming off.
+
+A live check sent simulated key events through the production plugin bridge to the open local Control Hub 0.0.001 test build, PowerPoint COM and OBS 33.0.1. Next/previous, go to slide, invalid-slide rejection, black screen/resume and OBS scene selection passed. Slide 1 and the original scene were restored. The presentation SHA-256 was unchanged. No recording or streaming was started. The check used the already open control window from package-001-b; installation checks of the new package are separate.
+
+The owner subsequently confirmed that the physical Next key on Stream Deck XL changes slides. The follow-up COM read did not find exactly one active slideshow, so the resulting slide number was not independently verified. Profile 2 has Status, Next, Previous, OBS SORT and OBS PPT. Physical presses on the other keys, recording, streaming, mute, animations and full hardware acceptance remain unconfirmed.
+
+On 1 November, 51 C# tests and 27 JavaScript tests pass after adding specific connection reasons. Tests cover missing/rejected OBS passwords, a closed port, malformed handshake, disconnect after dispatch, PowerPoint failure reasons and safe bilingual status messages. Fault tests use a simulated OBS server; they do not change the user's server settings.
+
+## AndroidRemote implementation stage — 1 November 2026
+
+After adding the AndroidRemote library, 89 C# tests and 27 JavaScript tests pass. The 38 new cases cover concurrent single-use pairing, expiry, wrong tokens, permissions, device limits, revocation during queueing/status reads, isolated duplicate history and unknown outcomes without automatic replay. Host smoke tests pass on a separate local port while the regular Control Hub runs. Build: zero warnings/errors. These are library tests with simulated devices, not Android hardware tests.
+
+## Phone dialog — 2 November 2026
+
+The Android APK was subsequently installed on an Android 15 test emulator. The test rejected an altered certificate fingerprint and then used the same invitation with the correct fingerprint. Next and Previous produced two navigations in total. One scene-button press produced one OBS switch. Status recovered after a network interruption with the original slide and selected scene. Counts did not increase after reconnecting or revoking access. The phone reloaded its encrypted session between trials. PowerPoint and OBS adapters used controlled test sessions.
+
+The host smoke test creates, lists and cancels test invitations and checks the capacity limit. Missing owner proof, the Stream Deck key alone, Origin requests and invalid fields are rejected. The listing contains no secrets or tokens. The packaged desktop client has a separate create/read/cancel check. The actual Windows dialog was visually checked in both languages with simulated devices, including Danish creation of a read-only invitation. No phone was used.
diff --git a/docs/versioning.md b/docs/versioning.md
new file mode 100644
index 0000000..0425a99
--- /dev/null
+++ b/docs/versioning.md
@@ -0,0 +1,21 @@
+# Versionsregler / Version policy
+
+## Dansk
+
+Den første udviklingsversion er **0.0.001**. `VERSION` og `HubVersion.Display` indeholder det brugervendte nummer. MSBuild/NuGet bruger normaliseret `0.0.1`; .NET assembly- og Stream Deck-manifestversioner bruger `0.0.1.0`.
+
+Alle versioner er udviklingsversioner, indtil ejeren har godkendt andet. **Ingen release eller tag uden udtrykkelig godkendelse.** Hver passage af en .100-grænse — eksempelvis 0.0.099 → 0.0.100 og 0.0.199 → 0.0.200 — kræver særskilt godkendelse, også uden en release. Nummeret er et aftalt fremdriftssignal og må ikke automatisk øges.
+
+**0.1.000** kræver, at det aftalte scope er fuldført, at test i det aktive miljø er dokumenteret og accepteret, og at ejeren udtrykkeligt godkender skiftet. Scope og acceptkriterier skal afklares, ikke antages.
+
+Der findes ingen release-, tag- eller automatisk versionsworkflow. CI kontrollerer aktuelt 0.0.001. En godkendt senere versionsændring skal opdatere versionsfelter, test, dokumentation og ændringslog samlet i en PR. Procesreglerne er ikke en GitHub-administratorlås; branch protection og ejerreview skal konfigureres særskilt, hvis håndhævelse ønskes.
+
+## English
+
+The first development version is **0.0.001**. `VERSION` and `HubVersion.Display` contain the user-facing number. MSBuild/NuGet use normalized `0.0.1`; .NET assembly and Stream Deck manifest versions use `0.0.1.0`.
+
+All versions remain development versions until the owner approves otherwise. **No release or tag without explicit approval.** Every .100 boundary — for example 0.0.099 → 0.0.100 and 0.0.199 → 0.0.200 — requires separate approval, even without a release. The number is an agreed progress signal and must not increment automatically.
+
+**0.1.000** requires completion of the agreed scope, documented and accepted testing in the active environment, and explicit owner approval of the transition. Scope and acceptance criteria must be established rather than assumed.
+
+There is no release, tag or automatic versioning workflow. CI currently checks 0.0.001. An approved future version change must update version fields, tests, documentation and changelog together in a PR. These process rules are not a GitHub administrator lock; branch protection and owner review must be configured separately if enforcement is required.
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..d46d21e
--- /dev/null
+++ b/global.json
@@ -0,0 +1,7 @@
+{
+ "sdk": {
+ "version": "10.0.100",
+ "rollForward": "latestFeature",
+ "allowPrerelease": false
+ }
+}
diff --git a/packaging/windows/ControlHub.iss b/packaging/windows/ControlHub.iss
new file mode 100644
index 0000000..05b00fc
--- /dev/null
+++ b/packaging/windows/ControlHub.iss
@@ -0,0 +1,60 @@
+; Dansk/English: Byg med scripts/package-windows.ps1 / Build with scripts/package-windows.ps1.
+#ifndef PayloadDir
+ #error PayloadDir is required
+#endif
+#ifndef OutputDir
+ #error OutputDir is required
+#endif
+
+[Setup]
+AppId={{87AF9AA0-6C89-4404-8BCD-9048AC911001}
+AppName=Control Hub
+AppVersion=0.0.001
+AppVerName=Control Hub 0.0.001
+AppPublisher=thebonden
+AppPublisherURL=https://github.com/thebonden/Control_Hub
+DefaultDirName={localappdata}\Programs\ControlHub
+DefaultGroupName=Control Hub
+PrivilegesRequired=lowest
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+MinVersion=10.0.17763
+OutputDir={#OutputDir}
+OutputBaseFilename=ControlHub-0.0.001-win-x64-Setup
+Compression=lzma2
+SolidCompression=yes
+WizardStyle=modern
+UninstallDisplayIcon={app}\ControlHub.exe
+CloseApplications=yes
+RestartApplications=no
+SetupLogging=yes
+
+[Languages]
+Name: "danish"; MessagesFile: "compiler:Languages\Danish.isl"
+Name: "english"; MessagesFile: "compiler:Default.isl"
+
+[CustomMessages]
+danish.DesktopShortcut=Opret en genvej på skrivebordet
+english.DesktopShortcut=Create a desktop shortcut
+danish.OpenHub=Åbn Control Hub
+english.OpenHub=Open Control Hub
+danish.Guide=Installationsvejledning
+english.Guide=Installation guide
+
+[Tasks]
+Name: "desktopicon"; Description: "{cm:DesktopShortcut}"; Flags: unchecked
+
+[Files]
+Source: "{#PayloadDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
+
+[Icons]
+Name: "{group}\Control Hub"; Filename: "{app}\ControlHub.exe"
+Name: "{group}\{cm:Guide}"; Filename: "{app}\docs\installation.da.html"; Languages: danish
+Name: "{group}\{cm:Guide}"; Filename: "{app}\docs\installation.en.html"; Languages: english
+Name: "{autodesktop}\Control Hub"; Filename: "{app}\ControlHub.exe"; Tasks: desktopicon
+
+[Run]
+Filename: "{app}\ControlHub.exe"; Description: "{cm:OpenHub}"; Flags: nowait postinstall skipifsilent unchecked
+
+; Bevar brugerens krypterede indstillinger og Stream Deck-profiler ved afinstallation.
+; Preserve encrypted user settings and Stream Deck profiles during uninstall.
diff --git a/scripts/android-emulator-ci.sh b/scripts/android-emulator-ci.sh
new file mode 100644
index 0000000..f3f4177
--- /dev/null
+++ b/scripts/android-emulator-ci.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+sdk="${ANDROID_HOME:?Android SDK required}"
+out="$RUNNER_TEMP/controlhub-android"
+export ANDROID_USER_HOME="$out/android-user"
+export ANDROID_EMULATOR_HOME="$ANDROID_USER_HOME"
+export ANDROID_AVD_HOME="$ANDROID_USER_HOME/avd"
+mkdir -p "$ANDROID_AVD_HOME"
+"$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-35" "build-tools;36.0.0" "system-images;android-35;google_atd;x86_64" emulator platform-tools
+build=(python3 Plugins/AndroidRemote/Android/build.py --sdk "$sdk" --jdk "$JAVA_HOME" --keystore "$out/dev.p12")
+"${build[@]}" --out "$out/ControlHub-AndroidRemote-0.0.001.apk"
+"${build[@]}" --ui-test --out "$out/ui-test.apk"
+
+sudo setfacl -m "u:$(id -un):rw" /dev/kvm
+avd="$ANDROID_AVD_HOME/ControlHubTrial.avd"
+echo no | "$sdk/cmdline-tools/latest/bin/avdmanager" create avd -n ControlHubTrial -p "$avd" -k "system-images;android-35;google_atd;x86_64" --device pixel_5
+test -f "$avd/config.ini"
+printf 'avd.ini.encoding=UTF-8\npath=%s\ntarget=android-35\n' "$avd" > "$ANDROID_AVD_HOME/ControlHubTrial.ini"
+"$sdk/emulator/emulator" -list-avds | grep -Fx ControlHubTrial
+"$sdk/emulator/emulator" -avd ControlHubTrial -port 5590 -no-window -no-audio -no-snapshot -no-boot-anim -gpu swiftshader -memory 2048 >"$out/emulator.log" 2>&1 &
+emulator_pid=$!
+trap 'kill "$emulator_pid" 2>/dev/null || true' EXIT
+adb="$sdk/platform-tools/adb"
+for attempt in {1..120}; do
+ if ! kill -0 "$emulator_pid" 2>/dev/null; then tail -40 "$out/emulator.log"; exit 1; fi
+ if [[ "$("$adb" -s emulator-5590 shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == 1 ]]; then
+ python3 tests/android-ui/run.py --serial emulator-5590 --adb "$adb" --apk "$out/ControlHub-AndroidRemote-0.0.001.apk" --test-apk "$out/ui-test.apk"
+ exit 0
+ fi
+ sleep 2
+done
+tail -40 "$out/emulator.log"
+exit 1
diff --git a/scripts/check-policy.cjs b/scripts/check-policy.cjs
new file mode 100644
index 0000000..b6a90cf
--- /dev/null
+++ b/scripts/check-policy.cjs
@@ -0,0 +1,18 @@
+const fs = require("node:fs");
+const path = require("node:path");
+const assert = require("node:assert/strict");
+const root = path.resolve(__dirname,"..");
+function walk(dir) {
+ return fs.readdirSync(dir,{withFileTypes:true}).flatMap(item => {
+ if([".git","bin","obj","node_modules","artifacts"].includes(item.name)) return [];
+ const file=path.join(dir,item.name);
+ return item.isDirectory()?walk(file):[file];
+ });
+}
+const files=walk(root);
+assert.ok(!files.some(file=>/\.(ppt|pptx|pptm|pps|ppsx|ppsm|pot|potx|potm)$/i.test(file)), "Presentation files are not source assets / Præsentationsfiler må ikke tilføjes");
+const source=files.filter(file=>file.includes(path.join("Plugins","PowerPoint"))&&file.endsWith(".cs")).map(file=>fs.readFileSync(file,"utf8")).join("\n");
+assert.ok(!/SendKeys|SendInput|keybd_event|SetForegroundWindow|\.Save\s*\(|\.SaveAs\s*\(|\.Open\s*\(|\.Quit\s*\(/.test(source), "Forbidden PowerPoint file/focus operation / Forbudt fil- eller fokusoperation");
+const version=fs.readFileSync(path.join(root,"VERSION"),"utf8").trim();
+assert.equal(version,"0.0.001", "Version changes require explicit review / Versionsændringer kræver eksplicit review");
+console.log("Source policy checks passed / Kildekoderegler bestået");
diff --git a/scripts/package-windows.ps1 b/scripts/package-windows.ps1
new file mode 100644
index 0000000..d6ffe76
--- /dev/null
+++ b/scripts/package-windows.ps1
@@ -0,0 +1,43 @@
+param(
+ [Parameter(Mandatory = $true)][string]$IsccPath,
+ [string]$OutputDirectory,
+ [switch]$UsePnpm
+)
+$ErrorActionPreference = 'Stop'
+$root = Split-Path $PSScriptRoot -Parent
+if (-not $OutputDirectory) { $OutputDirectory = Join-Path $root ('artifacts\windows-' + [Guid]::NewGuid().ToString('N')) }
+$output = [IO.Path]::GetFullPath($OutputDirectory)
+if (Test-Path -LiteralPath $output) { throw 'Brug en ny outputmappe / Use a new output directory' }
+if (-not (Test-Path -LiteralPath $IsccPath -PathType Leaf)) { throw 'ISCC.exe mangler / ISCC.exe missing' }
+if ((Get-Content (Join-Path $root 'VERSION') -Raw).Trim() -ne '0.0.001') { throw 'Versionsgodkendelse kræves / Version approval required' }
+$payload = Join-Path $output 'payload'
+$files = Join-Path $output 'files'
+$pluginOutput = Join-Path $payload 'Plugins\StreamDeck'
+New-Item -ItemType Directory -Path $payload,$files,$pluginOutput -Force | Out-Null
+Push-Location $root
+try {
+ & dotnet publish src/ControlHub.Host/ControlHub.Host.csproj -c Release -r win-x64 --self-contained true -o (Join-Path $payload 'host') -m:1 -nr:false
+ if ($LASTEXITCODE -ne 0) { throw 'Host publish failed / Host-pakning mislykkedes' }
+ & dotnet publish src/ControlHub.Desktop/ControlHub.Desktop.csproj -c Release -r win-x64 --self-contained true -o $payload -m:1 -nr:false
+ if ($LASTEXITCODE -ne 0) { throw 'Desktop publish failed / Desktop-pakning mislykkedes' }
+ # CLI may normalize manifest whitespace; package a copy to keep source unchanged.
+ # CLI kan normalisere manifestet; pak en kopi, så kilden ikke ændres.
+ $plugin = Join-Path $output 'source\Plugins\StreamDeck\dk.thebonden.controlhub.sdPlugin'
+ New-Item -ItemType Directory -Path (Split-Path $plugin -Parent) -Force | Out-Null
+ Copy-Item -LiteralPath (Join-Path $root 'Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin') -Destination $plugin -Recurse
+ if ($UsePnpm) {
+ & pnpm --package=@elgato/cli@1.10.3 dlx streamdeck pack --no-update-check --no-file-list $plugin --output $pluginOutput
+ } else {
+ & npx --yes --package=@elgato/cli@1.10.3 streamdeck pack --no-update-check --no-file-list $plugin --output $pluginOutput
+ }
+ if ($LASTEXITCODE -ne 0) { throw 'Stream Deck-pakning mislykkedes / Stream Deck packaging failed' }
+ Copy-Item -LiteralPath (Join-Path $root 'docs') -Destination (Join-Path $payload 'docs') -Recurse
+ Copy-Item -LiteralPath (Join-Path $root 'README.md'),(Join-Path $root 'README.en.md'),(Join-Path $root 'VERSION') -Destination $payload
+ Copy-Item -LiteralPath (Join-Path $pluginOutput 'dk.thebonden.controlhub.streamDeckPlugin') -Destination $files
+ & $IsccPath ("/DPayloadDir=$payload") ("/DOutputDir=$files") (Join-Path $root 'packaging/windows/ControlHub.iss')
+ if ($LASTEXITCODE -ne 0) { throw 'Installer-build mislykkedes / Installer build failed' }
+ Get-ChildItem -LiteralPath $files -File | Sort-Object Name | ForEach-Object {
+ '{0} {1}' -f (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name
+ } | Set-Content -LiteralPath (Join-Path $files 'SHA256SUMS.txt') -Encoding ascii
+ Write-Output "Installationsfiler / Installation files: $files"
+} finally { Pop-Location }
diff --git a/scripts/verify-package.ps1 b/scripts/verify-package.ps1
new file mode 100644
index 0000000..b269c7e
--- /dev/null
+++ b/scripts/verify-package.ps1
@@ -0,0 +1,22 @@
+param([Parameter(Mandatory = $true)][string]$PackageDirectory)
+$ErrorActionPreference = 'Stop'
+$package = [IO.Path]::GetFullPath($PackageDirectory)
+$payload = Join-Path $package 'payload'
+$resultDirectory = Join-Path $package ('verification-' + [Guid]::NewGuid().ToString('N'))
+foreach ($relative in @('ControlHub.exe','host\ControlHub.Host.exe','docs\installation.da.html','docs\installation.en.html','Plugins\StreamDeck\dk.thebonden.controlhub.streamDeckPlugin')) {
+ if (-not (Test-Path -LiteralPath (Join-Path $payload $relative) -PathType Leaf)) { throw "Pakkefil mangler / Missing package file: $relative" }
+}
+foreach ($relative in @('ControlHub.runtimeconfig.json','host\ControlHub.Host.runtimeconfig.json')) {
+ $runtime = Get-Content -LiteralPath (Join-Path $payload $relative) -Raw | ConvertFrom-Json
+ if ($runtime.runtimeOptions.framework -or $runtime.runtimeOptions.frameworks -or -not $runtime.runtimeOptions.includedFrameworks) {
+ throw 'Pakken skal inkludere .NET / Package must include .NET'
+ }
+}
+$test = Start-Process -FilePath (Join-Path $payload 'ControlHub.exe') -ArgumentList @('--self-test', ('"' + $resultDirectory + '"')) -WindowStyle Hidden -PassThru
+if (-not $test.WaitForExit(90000)) { throw 'Pakketest overskred tidsgrænsen / Package test timed out' }
+$test.Refresh()
+if ($test.ExitCode -ne 0) { throw "Pakketest fejlede / Package test failed: $resultDirectory" }
+$result = Get-Content -LiteralPath (Join-Path $resultDirectory 'result.json') -Raw | ConvertFrom-Json
+if (-not $result.passed) { throw 'Pakketest fejlede / Package test failed' }
+$result.checks
+Write-Output 'Pakketest bestået / Package test passed'
diff --git a/src/ControlHub.Contracts/ControlHub.Contracts.csproj b/src/ControlHub.Contracts/ControlHub.Contracts.csproj
new file mode 100644
index 0000000..6b512ec
--- /dev/null
+++ b/src/ControlHub.Contracts/ControlHub.Contracts.csproj
@@ -0,0 +1 @@
+
diff --git a/src/ControlHub.Contracts/Protocol.cs b/src/ControlHub.Contracts/Protocol.cs
new file mode 100644
index 0000000..f594fc8
--- /dev/null
+++ b/src/ControlHub.Contracts/Protocol.cs
@@ -0,0 +1,51 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace ControlHub.Contracts;
+
+public static class HubVersion
+{
+ public const string Display = "0.0.001";
+ public const string Protocol = "1";
+}
+
+public sealed record LocalizedText(string Da, string En);
+public sealed record Command(string ProtocolVersion, string Id, string Plugin, string Action, JsonElement Arguments);
+public sealed record CommandResult(string ProtocolVersion, string Id, string Plugin, bool Success,
+ string Code, LocalizedText Message, JsonElement? Data = null);
+public sealed record PluginStatus(string Id, string State, LocalizedText Message, JsonElement? Data = null);
+public sealed record PluginDescriptor(string Id, LocalizedText Name, string Maturity, IReadOnlyList Actions);
+public sealed record HubStatus(string ProtocolVersion, string Version, DateTimeOffset ObservedAt,
+ IReadOnlyList Plugins);
+
+public interface IHubPlugin : IAsyncDisposable
+{
+ PluginDescriptor Descriptor { get; }
+ ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken);
+ ValueTask GetStatusAsync(CancellationToken cancellationToken);
+}
+
+public static class Wire
+{
+ public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
+ {
+ UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
+ MaxDepth = 16
+ };
+ public static JsonElement Data(object value) => JsonSerializer.SerializeToElement(value, Json);
+ public static CommandResult Result(Command command, bool success, string code, string da, string en, object? data = null)
+ => new(HubVersion.Protocol, command.Id, command.Plugin, success, code, new(da, en),
+ data is null ? null : Data(data));
+ public static bool OnlyArguments(JsonElement args, params string[] allowed)
+ => args.ValueKind == JsonValueKind.Object &&
+ args.EnumerateObject().All(p => allowed.Contains(p.Name, StringComparer.Ordinal)) &&
+ args.EnumerateObject().Select(p => p.Name).Distinct(StringComparer.Ordinal).Count() == args.EnumerateObject().Count();
+ public static bool StringArgument(JsonElement args, string name, out string value)
+ {
+ value = "";
+ if (args.ValueKind != JsonValueKind.Object || !args.TryGetProperty(name, out var item) ||
+ item.ValueKind != JsonValueKind.String) return false;
+ value = item.GetString() ?? "";
+ return !string.IsNullOrWhiteSpace(value) && value.Length <= 256;
+ }
+}
diff --git a/src/ControlHub.Core/CommandDispatcher.cs b/src/ControlHub.Core/CommandDispatcher.cs
new file mode 100644
index 0000000..9efe888
--- /dev/null
+++ b/src/ControlHub.Core/CommandDispatcher.cs
@@ -0,0 +1,96 @@
+using System.Text.Json;
+using ControlHub.Contracts;
+
+namespace ControlHub.Core;
+
+// Explicit registration only: loading arbitrary DLLs would cross the trust boundary.
+// Kun eksplicit registrering: vilkårlige DLL-filer må ikke indlæses.
+public sealed class CommandDispatcher
+{
+ private readonly Dictionary plugins;
+ private readonly SemaphoreSlim gate = new(1);
+ private readonly Dictionary recent = new(StringComparer.Ordinal);
+ private readonly Queue order = new();
+ private readonly TimeSpan timeout;
+ public IReadOnlyList Descriptors => plugins.Values.Select(p => p.Descriptor).ToArray();
+
+ public CommandDispatcher(IEnumerable plugins, TimeSpan? timeout = null)
+ {
+ this.plugins = plugins.ToDictionary(p => p.Descriptor.Id, StringComparer.Ordinal);
+ this.timeout = timeout ?? TimeSpan.FromSeconds(10);
+ }
+
+ public async Task DispatchAsync(Command command, CancellationToken cancellationToken = default,
+ Func? authorizeBeforeDispatch = null)
+ {
+ if (command.ProtocolVersion != HubVersion.Protocol)
+ return Wire.Result(command, false, "unsupported_protocol", "Ukendt protokolversion.", "Unsupported protocol version.");
+ if (!Guid.TryParseExact(command.Id, "D", out _) || string.IsNullOrWhiteSpace(command.Plugin) ||
+ string.IsNullOrWhiteSpace(command.Action) || command.Arguments.ValueKind != JsonValueKind.Object)
+ return Wire.Result(command, false, "invalid_command", "Ugyldig kommando.", "Invalid command.");
+ if (!plugins.TryGetValue(command.Plugin, out var plugin))
+ return Wire.Result(command, false, "unknown_plugin", "Ukendt plugin.", "Unknown plugin.");
+ if (!plugin.Descriptor.Actions.Contains(command.Action, StringComparer.Ordinal))
+ return Wire.Result(command, false, "unsupported_action", "Handlingen understøttes ikke.", "Unsupported action.");
+
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(timeout);
+ try { await gate.WaitAsync(deadline.Token); }
+ catch (OperationCanceledException)
+ {
+ return Wire.Result(command, false, "cancelled_before_dispatch", "Ikke afsendt.", "Not dispatched.");
+ }
+ try
+ {
+ // Kontrollér adgang efter køen og før cache/udførelse, så tilbagekaldelse virker under ventetid.
+ // Recheck access after queueing and before cache/execution so revocation applies while waiting.
+ if (authorizeBeforeDispatch is not null && !authorizeBeforeDispatch())
+ return Wire.Result(command, false, "access_denied",
+ "Enheden har ikke adgang til handlingen. Kontrollér parring og rettigheder.",
+ "This device cannot use this action. Check pairing and permissions.");
+ var key = Guid.Parse(command.Id).ToString("D");
+ var fingerprint = JsonSerializer.Serialize(new { command.Plugin, command.Action, command.Arguments }, Wire.Json);
+ if (recent.TryGetValue(key, out var previous))
+ return previous.Fingerprint == fingerprint ? previous.Result :
+ Wire.Result(command, false, "id_conflict", "Id er allerede brugt til en anden kommando.", "Id already belongs to a different command.");
+ CommandResult result;
+ try { result = await plugin.ExecuteAsync(command, deadline.Token); }
+ catch (OperationCanceledException)
+ {
+ result = Wire.Result(command, false, "outcome_unknown",
+ "Tidsgrænse eller afbrydelse. Kontrollér status før en ny handling.",
+ "Timed out or cancelled. Check status before another action.");
+ }
+ catch (Exception)
+ {
+ result = Wire.Result(command, false, "plugin_error",
+ "Pluginfejl. Kontrollér status før en ny handling.", "Plugin error. Check status before another action.");
+ }
+ recent[key] = (fingerprint, result);
+ order.Enqueue(key);
+ if (order.Count > 1024) recent.Remove(order.Dequeue());
+ return result;
+ }
+ finally { gate.Release(); }
+ }
+
+ public async Task GetStatusAsync(CancellationToken cancellationToken = default)
+ {
+ var status = new List();
+ foreach (var plugin in plugins.Values)
+ {
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(timeout);
+ try { status.Add(await plugin.GetStatusAsync(deadline.Token)); }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ status.Add(new(plugin.Descriptor.Id, "unavailable", new("Status fik timeout.", "Status timed out.")));
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ status.Add(new(plugin.Descriptor.Id, "unavailable", new("Status kunne ikke læses.", "Status could not be read.")));
+ }
+ }
+ return new(HubVersion.Protocol, HubVersion.Display, DateTimeOffset.UtcNow, status);
+ }
+}
diff --git a/src/ControlHub.Core/ControlHub.Core.csproj b/src/ControlHub.Core/ControlHub.Core.csproj
new file mode 100644
index 0000000..8615c9e
--- /dev/null
+++ b/src/ControlHub.Core/ControlHub.Core.csproj
@@ -0,0 +1 @@
+
diff --git a/src/ControlHub.Desktop/ControlHub.Desktop.csproj b/src/ControlHub.Desktop/ControlHub.Desktop.csproj
new file mode 100644
index 0000000..9bfec31
--- /dev/null
+++ b/src/ControlHub.Desktop/ControlHub.Desktop.csproj
@@ -0,0 +1,12 @@
+
+
+ WinExe
+ net10.0-windows
+ true
+ true
+ ControlHub
+
+
+
+
+
diff --git a/src/ControlHub.Desktop/HostSession.cs b/src/ControlHub.Desktop/HostSession.cs
new file mode 100644
index 0000000..f4c4b83
--- /dev/null
+++ b/src/ControlHub.Desktop/HostSession.cs
@@ -0,0 +1,125 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using ControlHub.Plugins.AndroidRemote;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Sockets;
+using System.Text.Json;
+
+namespace ControlHub.Desktop;
+
+// Ejer kun processen, som dette vindue starter / Owns only the process started by this window.
+internal sealed class HostSession : IDisposable
+{
+ private Process? process;
+ private readonly HttpClient client = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }) { Timeout = TimeSpan.FromSeconds(35) };
+ private string? ownerKey;
+ public IRemoteOwnerClient RemoteOwner => IsRunning && ownerKey is not null
+ ? new RemoteOwnerClient(client, new Uri(apiBase + "androidremote/owner/"), ownerKey)
+ : throw new InvalidOperationException("Start Control Hub først / Start Control Hub first.");
+ private readonly int portNumber;
+ private readonly int phonePort;
+ private readonly string apiBase;
+ public bool IsRunning => process is { HasExited: false };
+
+ // Separat port til pakketest; brugergrænsefladen benytter altid standardporten.
+ // Separate port for package tests; the user interface always uses the default.
+ public HostSession(int portNumber = 5187, int phonePort = 5188)
+ {
+ if (portNumber is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(portNumber));
+ this.portNumber = portNumber;
+ this.phonePort = phonePort;
+ apiBase = $"http://127.0.0.1:{portNumber}/api/v1/";
+ }
+
+ public async Task StartAsync(Settings settings, IPAddress? phoneAddress = null)
+ {
+ settings.Validate();
+ if (IsRunning) return;
+ using (var port = new TcpClient())
+ {
+ try
+ {
+ await port.ConnectAsync(IPAddress.Loopback, portNumber);
+ throw new InvalidOperationException($"Port {portNumber} er optaget. Stop den anden host først. / Port {portNumber} is in use. Stop the other host first.");
+ }
+ catch (SocketException error) when (error.SocketErrorCode == SocketError.ConnectionRefused) { }
+ }
+ var executable = Path.Combine(AppContext.BaseDirectory, "host", "ControlHub.Host.exe");
+ var start = new ProcessStartInfo(executable)
+ {
+ WorkingDirectory = Path.GetDirectoryName(executable)!,
+ UseShellExecute = false, CreateNoWindow = true,
+ RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true
+ };
+ start.Environment["CONTROLHUB_TOKEN"] = settings.Token;
+ ownerKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
+ start.Environment["CONTROLHUB_OWNER_KEY"] = ownerKey;
+ start.Environment["CONTROLHUB_PORT"] = portNumber.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ start.Environment["CONTROLHUB_PHONE_PORT"] = phonePort.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ start.Environment.Remove("CONTROLHUB_PHONE_ADDRESS");
+ if (phoneAddress is not null)
+ {
+ if (!phoneAddress.Equals(IPAddress.Loopback) && !PhoneEndpoint.LocalAddresses().Contains(phoneAddress))
+ throw new InvalidOperationException("Netværket er ikke tilgængeligt / Network is unavailable.");
+ start.Environment["CONTROLHUB_PHONE_ADDRESS"] = phoneAddress.ToString();
+ }
+ start.Environment["CONTROLHUB_OBS_URL"] = settings.ObsUrl;
+ start.Environment["CONTROLHUB_OBS_PASSWORD"] = settings.ObsPassword;
+ start.Environment["CONTROLHUB_DESKTOP_LIFETIME"] = "stdin";
+ process?.Dispose();
+ process = Process.Start(start) ?? throw new InvalidOperationException("Start mislykkedes / Start failed");
+ // Dræn uden at gemme output; hemmeligheder må ikke ende i logfiler.
+ // Drain without persisting output; secrets must not end up in logs.
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", settings.Token);
+ try
+ {
+ for (var attempt = 0; attempt < 100; attempt++)
+ {
+ if (process.HasExited) throw new InvalidOperationException("Hosten stoppede under start / Host exited during startup");
+ try
+ {
+ using var response = await client.GetAsync(apiBase + "plugins");
+ if (response.IsSuccessStatusCode) return;
+ }
+ catch (HttpRequestException) { }
+ await Task.Delay(100);
+ }
+ throw new TimeoutException("Hosten svarede ikke / Host did not respond");
+ }
+ catch { await StopAsync(); throw; }
+ }
+
+ public async Task StatusAsync()
+ {
+ if (!IsRunning) throw new InvalidOperationException("Control Hub er stoppet / Control Hub is stopped");
+ using var response = await client.GetAsync(apiBase + "status");
+ response.EnsureSuccessStatusCode();
+ return JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ }
+
+ public async Task StopAsync()
+ {
+ ownerKey = null;
+ if (!IsRunning) return;
+ process!.StandardInput.Close();
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ try { await process.WaitForExitAsync(timeout.Token); }
+ catch (OperationCanceledException)
+ {
+ if (!process.HasExited) process.Kill();
+ await process.WaitForExitAsync();
+ }
+ }
+
+ public void Dispose()
+ {
+ // Closing the pipe also stops the child if this window crashes.
+ // Lukning af røret stopper også barnet, hvis vinduet går ned.
+ if (IsRunning) process!.StandardInput.Close();
+ process?.Dispose();
+ client.Dispose();
+ }
+}
diff --git a/src/ControlHub.Desktop/MainWindow.cs b/src/ControlHub.Desktop/MainWindow.cs
new file mode 100644
index 0000000..8f15f08
--- /dev/null
+++ b/src/ControlHub.Desktop/MainWindow.cs
@@ -0,0 +1,174 @@
+using System.Diagnostics;
+using System.Net;
+using ControlHub.Plugins.AndroidRemote;
+using ControlHub.Plugins.AndroidRemote.Desktop;
+
+namespace ControlHub.Desktop;
+
+internal sealed class MainWindow : Form
+{
+ private readonly SettingsStore store = new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ControlHub"));
+ private readonly HostSession host = new();
+ private Settings settings;
+ private readonly ComboBox language = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 150 };
+ private readonly TextBox obsUrl = new() { Width = 440 };
+ private readonly TextBox obsPassword = new() { Width = 440, UseSystemPasswordChar = true };
+ private readonly Label heading = new() { AutoSize = true, Font = new Font("Segoe UI", 18, FontStyle.Bold) };
+ private readonly Label introduction = new() { AutoSize = true, MaximumSize = new Size(700, 0) };
+ private readonly Label urlLabel = new() { AutoSize = true };
+ private readonly Label passwordLabel = new() { AutoSize = true };
+ private readonly Label status = new() { AutoSize = true, MaximumSize = new Size(700, 0), Padding = new Padding(0, 12, 0, 12) };
+ private readonly Button save = new() { AutoSize = true };
+ private readonly Button copy = new() { AutoSize = true };
+ private readonly Button start = new() { AutoSize = true };
+ private readonly Button stop = new() { AutoSize = true };
+ private readonly Button refresh = new() { AutoSize = true };
+ private readonly Button install = new() { AutoSize = true };
+ private readonly Button guide = new() { AutoSize = true };
+ private readonly Button phones = new() { AutoSize = true };
+ private readonly CheckBox phoneAccess = new() { AutoSize = true };
+ private readonly ComboBox phoneNetwork = new() { Width = 180, DropDownStyle = ComboBoxStyle.DropDownList };
+ private bool busy, closing, canClose;
+ private bool Danish => language.SelectedIndex != 1;
+ private string T(string da, string en) => Danish ? da : en;
+
+ public MainWindow()
+ {
+ settings = store.Load();
+ store.Save(settings);
+ Text = "Control Hub · 0.0.001";
+ ClientSize = new Size(760, 590);
+ MinimumSize = new Size(720, 600);
+ AutoScaleMode = AutoScaleMode.Dpi;
+ Font = new Font("Segoe UI", 10);
+ StartPosition = FormStartPosition.CenterScreen;
+ var layout = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown,
+ WrapContents = false, AutoScroll = true, Padding = new Padding(24) };
+ Controls.Add(layout);
+ language.Items.AddRange(["Dansk", "English"]);
+ language.SelectedIndex = settings.Language == "en" ? 1 : 0;
+ obsUrl.Text = settings.ObsUrl;
+ obsPassword.Text = settings.ObsPassword;
+ layout.Controls.AddRange([heading, introduction, language, urlLabel, obsUrl, passwordLabel, obsPassword]);
+ var settingsButtons = new FlowLayoutPanel { AutoSize = true, WrapContents = true, MaximumSize = new Size(700, 0) };
+ settingsButtons.Controls.AddRange([save, copy]);
+ layout.Controls.Add(settingsButtons);
+ var networkRow = new FlowLayoutPanel { AutoSize = true };
+ networkRow.Controls.AddRange([phoneAccess, phoneNetwork]);
+ layout.Controls.Add(networkRow);
+ foreach (var address in PhoneEndpoint.LocalAddresses()) phoneNetwork.Items.Add(address);
+ if (phoneNetwork.Items.Count > 0) phoneNetwork.SelectedIndex = 0;
+ phoneAccess.CheckedChanged += (_, _) => UpdateEnabled();
+ var hostButtons = new FlowLayoutPanel { AutoSize = true };
+ hostButtons.Controls.AddRange([start, stop, refresh]);
+ layout.Controls.Add(hostButtons);
+ layout.Controls.Add(status);
+ layout.Controls.Add(install);
+ layout.Controls.Add(phones);
+ layout.Controls.Add(guide);
+ language.SelectedIndexChanged += (_, _) => { Translate(); ShowStoppedOrRunning(); };
+ save.Click += async (_, _) => await RunAsync(() => { SaveSettings(); status.Text = T("Indstillinger gemt.", "Settings saved."); return Task.CompletedTask; });
+ copy.Click += async (_, _) => await RunAsync(() => { Clipboard.SetText(settings.Token); status.Text = T("Forbindelsesnøglen er kopieret. Indsæt den i Stream Deck-knappens tokenfelt, og tryk Gem.", "Connection key copied. Paste it into the Stream Deck key's token field, then click Save."); return Task.CompletedTask; });
+ start.Click += async (_, _) => await RunAsync(async () => { SaveSettings(); await host.StartAsync(settings, phoneAccess.Checked ? phoneNetwork.SelectedItem as IPAddress : null); await ShowStatusAsync(); });
+ stop.Click += async (_, _) => await RunAsync(async () => { await host.StopAsync(); ShowStoppedOrRunning(); });
+ refresh.Click += async (_, _) => await RunAsync(ShowStatusAsync);
+ phones.Click += (_, _) =>
+ {
+ if (!host.IsRunning) { ShowStoppedOrRunning(); UpdateEnabled(); return; }
+ using var dialog = new PhoneAccessWindow(host.RemoteOwner, Danish);
+ dialog.ShowDialog(this);
+ UpdateEnabled();
+ };
+ install.Click += async (_, _) => await RunAsync(() => OpenFile(Path.Combine("Plugins", "StreamDeck", "dk.thebonden.controlhub.streamDeckPlugin")));
+ guide.Click += async (_, _) => await RunAsync(() => OpenFile(Path.Combine("docs", Danish ? "installation.da.html" : "installation.en.html")));
+ FormClosing += async (_, e) =>
+ {
+ if (canClose) return;
+ e.Cancel = true;
+ if (closing) return;
+ closing = true;
+ Enabled = false;
+ // Wait for the active UI operation before stopping its child.
+ // Vent på den aktive UI-handling, før dens underproces stoppes.
+ while (busy) await Task.Delay(50);
+ try { await host.StopAsync(); }
+ catch { closing = false; Enabled = true; status.Text = T("Kunne ikke stoppe hosten. Prøv Stop igen.", "Could not stop the host. Try Stop again."); return; }
+ host.Dispose();
+ canClose = true;
+ Close();
+ };
+ Translate();
+ ShowStoppedOrRunning();
+ }
+
+ private void Translate()
+ {
+ heading.Text = "Control Hub · 0.0.001";
+ introduction.Text = T("Udviklingsversion · Stream Deck, PowerPoint og OBS Studio\nStart selv ét slideshow. Hold dette vindue åbent under brug.", "Development build · Stream Deck, PowerPoint and OBS Studio\nStart one slideshow manually. Keep this window open during use.");
+ urlLabel.Text = T("OBS WebSocket-adresse (på denne computer)", "OBS WebSocket address (on this computer)");
+ passwordLabel.Text = T("OBS WebSocket-adgangskode", "OBS WebSocket password");
+ save.Text = T("Gem indstillinger", "Save settings");
+ copy.Text = T("Kopiér forbindelsesnøgle", "Copy connection key");
+ start.Text = T("Start Control Hub", "Start Control Hub");
+ stop.Text = T("Stop Control Hub", "Stop Control Hub");
+ refresh.Text = T("Kontrollér forbindelse", "Check connection");
+ install.Text = T("Installér Stream Deck-plugin", "Install Stream Deck plugin");
+ guide.Text = T("Åbn installationsvejledning", "Open installation guide");
+ phoneAccess.Text = T("Tillad AndroidRemote på lokalt netværk", "Allow AndroidRemote on local network");
+ phoneNetwork.AccessibleName = T("Netværksadresse til telefon", "Network address for phone");
+ phones.Text = T("Administrér telefonadgang", "Manage phone access");
+ UpdateEnabled();
+ }
+
+ private void SaveSettings()
+ {
+ var updated = settings with { ObsUrl = obsUrl.Text.Trim(), ObsPassword = obsPassword.Text, Language = Danish ? "da" : "en" };
+ store.Save(updated);
+ settings = updated;
+ }
+
+ private async Task RunAsync(Func action)
+ {
+ if (busy || closing) return;
+ busy = true;
+ UpdateEnabled();
+ status.Text = T("Arbejder…", "Working…");
+ try { await action(); }
+ catch (InvalidDataException) { status.Text = T("Kontrollér OBS-adressen: brug ws://127.0.0.1:4455 eller din lokale OBS-port.", "Check the OBS address: use ws://127.0.0.1:4455 or your local OBS port."); }
+ catch { status.Text = T("Handlingen mislykkedes. Kontrollér, om en anden Control Hub bruger port 5187, og se vejledningen.", "Operation failed. Check whether another Control Hub is using port 5187 and see the guide."); }
+ finally { busy = false; UpdateEnabled(); }
+ }
+
+ private async Task ShowStatusAsync()
+ {
+ using var document = await host.StatusAsync();
+ var lines = new List { T("Control Hub svarer · ", "Control Hub responds · ") + document.RootElement.GetProperty("version").GetString() };
+ foreach (var plugin in document.RootElement.GetProperty("plugins").EnumerateArray())
+ {
+ var id = plugin.GetProperty("id").GetString();
+ if (id is not ("powerpoint" or "obs")) continue;
+ lines.Add((id == "obs" ? "OBS Studio: " : "PowerPoint: ") + plugin.GetProperty("message").GetProperty(Danish ? "da" : "en").GetString());
+ }
+ status.Text = string.Join(Environment.NewLine, lines);
+ }
+
+ private void ShowStoppedOrRunning() => status.Text = host.IsRunning
+ ? T("Control Hub kører. Kontrollér forbindelsen for aktuel status.", "Control Hub is running. Check connection for current status.")
+ : T("Control Hub er stoppet. Gem indstillingerne, og tryk Start.", "Control Hub is stopped. Save settings, then click Start.");
+
+ private void UpdateEnabled()
+ {
+ var running = host.IsRunning;
+ phoneAccess.Enabled = !busy && !running && phoneNetwork.Items.Count > 0;
+ phoneNetwork.Enabled = phoneAccess.Enabled && phoneAccess.Checked;
+ start.Enabled = save.Enabled = obsUrl.Enabled = obsPassword.Enabled = !busy && !running;
+ stop.Enabled = refresh.Enabled = phones.Enabled = !busy && running;
+ copy.Enabled = install.Enabled = guide.Enabled = language.Enabled = !busy;
+ }
+
+ private static Task OpenFile(string relative)
+ {
+ Process.Start(new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, relative)) { UseShellExecute = true });
+ return Task.CompletedTask;
+ }
+}
diff --git a/src/ControlHub.Desktop/PackageSelfTest.cs b/src/ControlHub.Desktop/PackageSelfTest.cs
new file mode 100644
index 0000000..ab48436
--- /dev/null
+++ b/src/ControlHub.Desktop/PackageSelfTest.cs
@@ -0,0 +1,111 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Net;
+using System.Net.Sockets;
+using System.Net.Http.Json;
+using System.Net.Security;
+using System.Net.Http.Headers;
+
+namespace ControlHub.Desktop;
+
+// Køres eksplicit mod en separat testmappe; sender ingen produktionskommandoer.
+// Explicitly run against a separate test folder; sends no production commands.
+internal static class PackageSelfTest
+{
+ public static async Task RunAsync(string outputDirectory)
+ {
+ Directory.CreateDirectory(outputDirectory);
+ var checks = new List();
+ try
+ {
+ var settingsDirectory = Path.Combine(outputDirectory, Guid.NewGuid().ToString("N"));
+ var store = new SettingsStore(settingsDirectory);
+ var original = Settings.Create() with { ObsUrl = "ws://127.0.0.1:1", ObsPassword = "self-test-only", Language = "en" };
+ store.Save(original);
+ if (store.Load() != original) throw new InvalidDataException("Settings round trip failed");
+ var settingsFile = Path.Combine(settingsDirectory, "settings.dat");
+ var encrypted = File.ReadAllBytes(settingsFile);
+ if (Encoding.UTF8.GetString(encrypted).Contains(original.Token, StringComparison.Ordinal)) throw new InvalidDataException("Plaintext token");
+ checks.Add("DPAPI settings round trip; no plaintext token");
+ foreach (var invalid in new[] { "ws://example.com:4455", "wss://127.0.0.1:4455", "ws://127.0.0.1:4455/path", "ws://user@127.0.0.1:4455" })
+ {
+ try { (original with { ObsUrl = invalid }).Validate(); throw new Exception("Invalid URL accepted"); }
+ catch (InvalidDataException) { }
+ }
+ checks.Add("Nonlocal and unsupported OBS addresses rejected");
+ encrypted[encrypted.Length / 2] ^= 0xff;
+ File.WriteAllBytes(settingsFile, encrypted);
+ try { store.Load(); throw new InvalidDataException("Corrupt settings accepted"); }
+ catch (CryptographicException) { checks.Add("Corrupt encrypted settings rejected"); }
+ store.Save(original);
+ using var reservation = new TcpListener(IPAddress.Loopback, 0);
+ reservation.Start();
+ var testPort = ((IPEndPoint)reservation.LocalEndpoint).Port;
+ reservation.Stop();
+ // Hvis porten overtages i mellemtiden, fejler testen sikkert ved HostSessions portkontrol.
+ // If another process takes the port, HostSession's occupied-port check fails safely.
+ using var host = new HostSession(testPort, phonePort: 0);
+ await host.StartAsync(original, IPAddress.Loopback);
+ try
+ {
+ using var status = await host.StatusAsync();
+ if (status.RootElement.GetProperty("version").GetString() != "0.0.001") throw new InvalidDataException("Wrong version");
+ var obs = status.RootElement.GetProperty("plugins").EnumerateArray().Single(p => p.GetProperty("id").GetString() == "obs");
+ if (obs.GetProperty("state").GetString() != "unavailable") throw new InvalidDataException("OBS isolation failed");
+ var remote = status.RootElement.GetProperty("plugins").EnumerateArray().Single(p => p.GetProperty("id").GetString() == "androidremote");
+ if (remote.GetProperty("state").GetString() != "ready")
+ throw new InvalidDataException("AndroidRemote HTTPS listener failed");
+ checks.Add("Published phone listener starts on an isolated TLS port");
+ var owner = host.RemoteOwner;
+ var invite = await owner.BeginAsync("Package test", ["status.read"]);
+ var snapshot = await owner.GetAsync();
+ if (!snapshot.PendingPairings.Any(p => p.Id == invite.Id && p.Name == "Package test") ||
+ !snapshot.TransportReady || JsonSerializer.Serialize(snapshot).Contains(invite.Secret, StringComparison.Ordinal))
+ throw new InvalidDataException("Owner invitation status failed");
+ var connection = invite.Transport ?? throw new InvalidDataException("Missing phone address");
+ using var phone = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false,
+ ServerCertificateCustomValidationCallback = (_, cert, _, errors) =>
+ (errors & ~SslPolicyErrors.RemoteCertificateChainErrors) == 0 && cert is not null &&
+ cert.GetCertHashString(HashAlgorithmName.SHA256) == connection.CertificateSha256 })
+ { BaseAddress = new Uri(connection.Endpoint) };
+ using var claim = await phone.PostAsJsonAsync("/phone/v1/pair", new { invite.Id, invite.Secret });
+ claim.EnsureSuccessStatusCode();
+ using var credential = JsonDocument.Parse(await claim.Content.ReadAsStringAsync());
+ var deviceId = credential.RootElement.GetProperty("device").GetProperty("id").GetString()!;
+ phone.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credential.RootElement.GetProperty("token").GetString());
+ phone.DefaultRequestHeaders.Add("X-ControlHub-Device", deviceId);
+ using var phoneStatus = await phone.GetAsync("/phone/v1/status");
+ phoneStatus.EnsureSuccessStatusCode();
+ using var denied = await phone.PostAsJsonAsync("/phone/v1/commands", new { protocolVersion = "1",
+ id = Guid.NewGuid().ToString("D"), plugin = "powerpoint", action = "next", arguments = new { } });
+ if (denied.StatusCode != HttpStatusCode.Forbidden) throw new InvalidDataException("Phone permission boundary failed");
+ using var isolated = await phone.GetAsync("/api/v1/plugins");
+ if (isolated.StatusCode != HttpStatusCode.NotFound) throw new InvalidDataException("Desktop route exposed on phone port");
+ await owner.RemoveAsync(deviceId, pending: false);
+ using var revoked = await phone.GetAsync("/phone/v1/status");
+ if (revoked.StatusCode != HttpStatusCode.Unauthorized) throw new InvalidDataException("Revoked device accepted");
+ checks.Add("Pinned TLS pairing, status, denied command, route isolation and revocation");
+ var cancelled = await owner.BeginAsync("Cancel", ["status.read"]);
+ await owner.RemoveAsync(cancelled.Id, pending: true);
+ if ((await owner.GetAsync()).PendingPairings.Count != 0) throw new InvalidDataException("Owner cancellation failed");
+ checks.Add("Desktop owner creates, lists and cancels an invitation; the secret is absent from lists");
+ checks.Add("Published host starts; authenticated status works; test OBS is isolated");
+ using var other = new HostSession(testPort);
+ try { await other.StartAsync(original); throw new Exception("Duplicate host accepted"); }
+ catch (InvalidOperationException) { checks.Add("Occupied port rejected without stopping existing host"); }
+ using var stillRunning = await host.StatusAsync();
+ }
+ finally { await host.StopAsync(); }
+ if (host.IsRunning) throw new InvalidDataException("Host did not stop");
+ checks.Add("Owned host shuts down when stdin closes");
+ File.WriteAllText(Path.Combine(outputDirectory, "result.json"), JsonSerializer.Serialize(new { passed = true, checks }));
+ return 0;
+ }
+ catch (Exception error)
+ {
+ File.WriteAllText(Path.Combine(outputDirectory, "result.json"), JsonSerializer.Serialize(new { passed = false, checks, error = error.GetType().Name }));
+ return 1;
+ }
+ }
+}
diff --git a/src/ControlHub.Desktop/Program.cs b/src/ControlHub.Desktop/Program.cs
new file mode 100644
index 0000000..95883ed
--- /dev/null
+++ b/src/ControlHub.Desktop/Program.cs
@@ -0,0 +1,24 @@
+namespace ControlHub.Desktop;
+
+internal static class Program
+{
+ [STAThread]
+ private static int Main(string[] args)
+ {
+ if (args.Length == 2 && args[0] == "--self-test")
+ return PackageSelfTest.RunAsync(args[1]).GetAwaiter().GetResult();
+ ApplicationConfiguration.Initialize();
+ using var singleton = new Mutex(true, @"Local\ControlHub.Desktop.0.0.001", out var first);
+ if (!first)
+ {
+ MessageBox.Show("Control Hub er allerede åbent. / Control Hub is already open.", "Control Hub");
+ return 0;
+ }
+ try { Application.Run(new MainWindow()); return 0; }
+ catch
+ {
+ MessageBox.Show("Control Hub kunne ikke åbnes. Indstillingerne er ikke ændret. Se installationsvejledningen.\nControl Hub could not open. Settings have not been changed. See the installation guide.", "Control Hub");
+ return 1;
+ }
+ }
+}
diff --git a/src/ControlHub.Desktop/Settings.cs b/src/ControlHub.Desktop/Settings.cs
new file mode 100644
index 0000000..4d42bec
--- /dev/null
+++ b/src/ControlHub.Desktop/Settings.cs
@@ -0,0 +1,51 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+
+namespace ControlHub.Desktop;
+
+internal sealed record Settings(string Token, string ObsUrl, string ObsPassword, string Language)
+{
+ public static Settings Create() => new(Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
+ "ws://127.0.0.1:4455", "", "da");
+
+ public void Validate()
+ {
+ if (Token.Length < 32 || Language is not ("da" or "en") ||
+ !Uri.TryCreate(ObsUrl, UriKind.Absolute, out var endpoint) ||
+ !endpoint.IsLoopback || endpoint.Scheme != "ws" || endpoint.UserInfo.Length != 0 ||
+ endpoint.AbsolutePath != "/" || endpoint.Query.Length != 0 || endpoint.Fragment.Length != 0)
+ throw new InvalidDataException("Ugyldige indstillinger / Invalid settings");
+ }
+}
+
+internal sealed class SettingsStore(string directory)
+{
+ private readonly string file = Path.Combine(directory, "settings.dat");
+ public Settings Load()
+ {
+ if (!File.Exists(file)) return Settings.Create();
+ var plain = ProtectedData.Unprotect(File.ReadAllBytes(file), null, DataProtectionScope.CurrentUser);
+ try
+ {
+ var value = JsonSerializer.Deserialize(plain) ?? throw new InvalidDataException();
+ value.Validate();
+ return value;
+ }
+ finally { CryptographicOperations.ZeroMemory(plain); }
+ }
+
+ public void Save(Settings settings)
+ {
+ settings.Validate();
+ Directory.CreateDirectory(directory);
+ var plain = JsonSerializer.SerializeToUtf8Bytes(settings);
+ try
+ {
+ var encrypted = ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser);
+ var temporary = file + ".tmp";
+ File.WriteAllBytes(temporary, encrypted);
+ File.Move(temporary, file, true);
+ }
+ finally { CryptographicOperations.ZeroMemory(plain); }
+ }
+}
diff --git a/src/ControlHub.Host/ControlHub.Host.csproj b/src/ControlHub.Host/ControlHub.Host.csproj
new file mode 100644
index 0000000..4a562aa
--- /dev/null
+++ b/src/ControlHub.Host/ControlHub.Host.csproj
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ControlHub.Host/Program.cs b/src/ControlHub.Host/Program.cs
new file mode 100644
index 0000000..bf4b29b
--- /dev/null
+++ b/src/ControlHub.Host/Program.cs
@@ -0,0 +1,101 @@
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Threading.RateLimiting;
+using ControlHub.Contracts;
+using ControlHub.Core;
+using ControlHub.Plugins.AndroidRemote;
+using ControlHub.Plugins.AndroidRemote.Host;
+using ControlHub.Plugins.Obs;
+using ControlHub.Plugins.Planned;
+using ControlHub.Plugins.PowerPoint;
+using Microsoft.AspNetCore.RateLimiting;
+
+var token = Environment.GetEnvironmentVariable("CONTROLHUB_TOKEN");
+if (string.IsNullOrWhiteSpace(token) || token.Length < 32)
+ throw new InvalidOperationException("CONTROLHUB_TOKEN skal være mindst 32 tegn / CONTROLHUB_TOKEN must be at least 32 characters.");
+var tokenHash = SHA256.HashData(Encoding.UTF8.GetBytes("Bearer " + token));
+var portText = Environment.GetEnvironmentVariable("CONTROLHUB_PORT") ?? "5187";
+if (!int.TryParse(portText, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture,
+ out var port) || port is < 0 or > 65535)
+ throw new InvalidOperationException("Ugyldig lokal port / Invalid local port.");
+var builder = WebApplication.CreateBuilder(args);
+builder.WebHost.ConfigureKestrel(options =>
+{
+ options.Listen(IPAddress.Loopback, port);
+ options.Limits.MaxRequestBodySize = 16 * 1024;
+});
+builder.Services.AddRateLimiter(options =>
+{
+ options.RejectionStatusCode = 429;
+ options.AddConcurrencyLimiter("local", limiter => { limiter.PermitLimit = 8; limiter.QueueLimit = 0; limiter.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; });
+});
+builder.Services.ConfigureHttpJsonOptions(options =>
+{
+ options.SerializerOptions.UnmappedMemberHandling = Wire.Json.UnmappedMemberHandling;
+ options.SerializerOptions.MaxDepth = 16;
+});
+var remoteDevices = new RemoteDeviceRegistry();
+var plugins = new IHubPlugin[]
+{
+ new PowerPointPlugin(),
+ new ObsPlugin(new ObsClient(new Uri(Environment.GetEnvironmentVariable("CONTROLHUB_OBS_URL") ?? "ws://127.0.0.1:4455"),
+ Environment.GetEnvironmentVariable("CONTROLHUB_OBS_PASSWORD"))),
+ new AndroidRemotePlugin(remoteDevices),
+ new PlannedPlugin("audio", new("Lyd", "Audio")),
+ new PlannedPlugin("logitech", new("Logitech", "Logitech")),
+ new PlannedPlugin("android-live", new("Android Live", "Android Live")),
+ new PlannedPlugin("physical-remote", new("Fysisk fjernkontrol", "Physical remote")),
+ new PlannedPlugin("flux-keyboard", new("Flux Keyboard", "Flux Keyboard"))
+};
+var dispatcher = new CommandDispatcher(plugins);
+var app = builder.Build();
+// Desktop ejer hostens levetid. EOF efter normal lukning eller nedbrud stopper kun hosten.
+// Desktop owns host lifetime. EOF after normal close or a crash stops only the host.
+if (Environment.GetEnvironmentVariable("CONTROLHUB_DESKTOP_LIFETIME") == "stdin")
+ _ = Task.Run(async () =>
+ {
+ var input = new char[1];
+ while (await Console.In.ReadAsync(input.AsMemory()) != 0) { }
+ app.Lifetime.StopApplication();
+ });
+app.Use(async (context, next) =>
+{
+ // Reject browser-originated requests; Stream Deck uses its Node runtime.
+ // Afvis browserkald; Stream Deck benytter sin Node-runtime.
+ if (context.Request.Headers.ContainsKey("Origin")) { context.Response.StatusCode = 403; return; }
+ var supplied = SHA256.HashData(Encoding.UTF8.GetBytes(context.Request.Headers.Authorization.ToString()));
+ if (!CryptographicOperations.FixedTimeEquals(tokenHash, supplied))
+ {
+ context.Response.StatusCode = 401;
+ await context.Response.WriteAsJsonAsync(new { code = "unauthorized", message = new LocalizedText("Adgang afvist.", "Access denied.") });
+ return;
+ }
+ await next();
+});
+app.UseRateLimiter();
+var ownerKey = Environment.GetEnvironmentVariable("CONTROLHUB_OWNER_KEY");
+if (ownerKey is { Length: 64 } && ownerKey.All(char.IsAsciiHexDigit) && !string.Equals(ownerKey, token, StringComparison.OrdinalIgnoreCase))
+ app.MapAndroidRemoteOwner(remoteDevices, ownerKey);
+app.MapGet("/api/v1/plugins", () => dispatcher.Descriptors).RequireRateLimiting("local");
+app.MapGet("/api/v1/status", (CancellationToken ct) => dispatcher.GetStatusAsync(ct)).RequireRateLimiting("local");
+app.MapPost("/api/v1/commands", async (HttpRequest request, CancellationToken ct) =>
+{
+ Command? command;
+ try { command = await JsonSerializer.DeserializeAsync(request.Body, Wire.Json, ct); }
+ catch (JsonException) { return Results.BadRequest(new { code = "invalid_json", message = new LocalizedText("Ugyldig JSON.", "Invalid JSON.") }); }
+ if (command is null) return Results.BadRequest(new { code = "invalid_command", message = new LocalizedText("Kommando mangler.", "Missing command.") });
+ return Results.Json(await dispatcher.DispatchAsync(command, ct), Wire.Json);
+}).RequireRateLimiting("local");
+var phoneAddress = Environment.GetEnvironmentVariable("CONTROLHUB_PHONE_ADDRESS");
+var phonePortText = Environment.GetEnvironmentVariable("CONTROLHUB_PHONE_PORT") ?? "5188";
+if (!int.TryParse(phonePortText, out var phonePort) || phonePort is < 0 or > 65535)
+ throw new InvalidOperationException("Ugyldig telefonport / Invalid phone port.");
+try
+{
+ await using var phoneServer = string.IsNullOrWhiteSpace(phoneAddress) ? null :
+ await PhoneServer.StartAsync(IPAddress.Parse(phoneAddress), phonePort, remoteDevices, dispatcher);
+ await app.RunAsync();
+}
+finally { foreach (var plugin in plugins) await plugin.DisposeAsync(); }
diff --git a/tests/ControlHub.Tests/AndroidRemoteTests.cs b/tests/ControlHub.Tests/AndroidRemoteTests.cs
new file mode 100644
index 0000000..ef93611
--- /dev/null
+++ b/tests/ControlHub.Tests/AndroidRemoteTests.cs
@@ -0,0 +1,345 @@
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Core;
+using ControlHub.Plugins.AndroidRemote;
+using Xunit;
+
+namespace ControlHub.Tests;
+
+public sealed class AndroidRemoteTests
+{
+ [Fact]
+ public void PairingIsSingleUseAndCredentialsDoNotAppearInDeviceListsOrToString()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var offer = registry.BeginPairing(" Telefon ", [RemotePermissions.Status, RemotePermissions.PowerPoint]);
+ Assert.Equal(64, offer.Secret.Length);
+ Assert.DoesNotContain(offer.Secret, offer.ToString()!);
+ var paired = Assert.IsType(registry.CompletePairing(offer.Id, offer.Secret));
+ Assert.Equal("Telefon", paired.Device.Name);
+ Assert.NotEqual(offer.Secret, paired.Token);
+ Assert.DoesNotContain(paired.Token, paired.ToString()!);
+ Assert.Null(registry.CompletePairing(offer.Id, offer.Secret));
+ Assert.False(registry.Allows(paired.Device.Id, offer.Secret, RemotePermissions.Status));
+ Assert.True(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Status));
+ Assert.False(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Streaming));
+ var list = JsonSerializer.Serialize(registry.ListDevices(), Wire.Json);
+ Assert.DoesNotContain(offer.Secret, list);
+ Assert.DoesNotContain(paired.Token, list);
+ Assert.Equal(0, registry.PendingCount);
+ }
+
+ [Fact]
+ public async Task SimultaneousPairingAttemptsIssueExactlyOneCredential()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var offer = registry.BeginPairing("Phone", [RemotePermissions.Status]);
+ var results = await Task.WhenAll(Enumerable.Range(0, 32)
+ .Select(_ => Task.Run(() => registry.CompletePairing(offer.Id, offer.Secret))));
+ Assert.Single(results.OfType());
+ Assert.Single(registry.ListDevices());
+ }
+
+ [Fact]
+ public void FailedAttemptsExhaustOnlyTheTargetPairing()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var offer = registry.BeginPairing("Phone", [RemotePermissions.Status]);
+ var other = registry.BeginPairing("Other", [RemotePermissions.Status]);
+ for (var i = 0; i < RemoteDeviceRegistry.MaximumPairingAttempts; i++)
+ Assert.Null(registry.CompletePairing(offer.Id, i % 2 == 0 ? "bad" : new string('0', 64)));
+ Assert.Null(registry.CompletePairing(offer.Id, offer.Secret));
+ Assert.NotNull(registry.CompletePairing(other.Id, other.Secret));
+ Assert.Null(registry.CompletePairing(null, null));
+ }
+
+ [Fact]
+ public void PairingAndDeviceExpireAtTheirBoundariesDespiteWallClockChanges()
+ {
+ var clock = new TestClock();
+ var registry = new RemoteDeviceRegistry(clock);
+ var paired = Pair(registry, RemotePermissions.Status);
+ var offer = registry.BeginPairing("Expired", [RemotePermissions.Status]);
+ clock.Advance(RemoteDeviceRegistry.PairingLifetime - TimeSpan.FromTicks(1));
+ Assert.Equal(1, registry.PendingCount);
+ clock.Advance(TimeSpan.FromTicks(1));
+ clock.Utc -= TimeSpan.FromDays(1);
+ Assert.Null(registry.CompletePairing(offer.Id, offer.Secret));
+ Assert.True(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Status));
+ clock.Advance(RemoteDeviceRegistry.DeviceLifetime - RemoteDeviceRegistry.PairingLifetime);
+ Assert.False(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Status));
+ Assert.Empty(registry.ListDevices());
+ }
+
+ [Fact]
+ public void OwnerCanCancelPairingRevokeOneDeviceAndRevokeEverything()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var first = Pair(registry, RemotePermissions.Status);
+ var second = Pair(registry, RemotePermissions.Status);
+ var offer = registry.BeginPairing("Cancel", [RemotePermissions.Status]);
+ Assert.True(registry.CancelPairing(offer.Id));
+ Assert.False(registry.CancelPairing(offer.Id));
+ Assert.Null(registry.CompletePairing(offer.Id, offer.Secret));
+ Assert.True(registry.RevokeDevice(first.Device.Id));
+ Assert.False(registry.RevokeDevice(first.Device.Id));
+ Assert.False(registry.Allows(first.Device.Id, first.Token, RemotePermissions.Status));
+ Assert.True(registry.Allows(second.Device.Id, second.Token, RemotePermissions.Status));
+ var pending = registry.BeginPairing("Pending", [RemotePermissions.Status]);
+ registry.RevokeAll();
+ Assert.False(registry.Allows(second.Device.Id, second.Token, RemotePermissions.Status));
+ Assert.Null(registry.CompletePairing(pending.Id, pending.Secret));
+ Assert.Empty(registry.ListDevices());
+ Assert.Equal(0, registry.PendingCount);
+ Assert.False(new RemoteDeviceRegistry().Allows(second.Device.Id, second.Token, RemotePermissions.Status));
+ }
+
+ [Fact]
+ public void RegistriesHaveBoundedCapacityAndReservePendingDeviceSlots()
+ {
+ var clock = new TestClock();
+ var registry = new RemoteDeviceRegistry(clock);
+ var pending = Enumerable.Range(0, RemoteDeviceRegistry.MaximumPendingPairings)
+ .Select(_ => registry.BeginPairing("Phone", [RemotePermissions.Status])).ToArray();
+ Assert.Throws(() => registry.BeginPairing("Overflow", [RemotePermissions.Status]));
+ foreach (var offer in pending) Assert.NotNull(registry.CompletePairing(offer.Id, offer.Secret));
+ for (var i = pending.Length; i < RemoteDeviceRegistry.MaximumDevices; i++) Pair(registry, RemotePermissions.Status);
+ Assert.Throws(() => registry.BeginPairing("Overflow", [RemotePermissions.Status]));
+ clock.Advance(RemoteDeviceRegistry.DeviceLifetime);
+ Assert.NotNull(registry.BeginPairing("Fresh", [RemotePermissions.Status]));
+ }
+
+ [Theory]
+ [InlineData("")][InlineData(" ")][InlineData("Phone\nName")]
+ public void InvalidDeviceNamesCannotOpenPairing(string name)
+ => Assert.Throws(() => new RemoteDeviceRegistry().BeginPairing(name, [RemotePermissions.Status]));
+
+ [Fact]
+ public void OwnerPermissionsAreValidatedAndCannotBeMutatedAfterPairing()
+ {
+ var registry = new RemoteDeviceRegistry();
+ Assert.Throws(() => registry.BeginPairing(new string('x', 81), [RemotePermissions.Status]));
+ Assert.Throws(() => registry.BeginPairing("Phone", []));
+ Assert.Throws(() => registry.BeginPairing("Phone", ["*"]));
+ Assert.Throws(() => registry.BeginPairing("Phone", [RemotePermissions.Status, RemotePermissions.Status]));
+ string[] permissions = [RemotePermissions.Status];
+ var offer = registry.BeginPairing("Phone", permissions);
+ permissions[0] = RemotePermissions.Streaming;
+ var paired = registry.CompletePairing(offer.Id, offer.Secret)!;
+ Assert.Throws(() => ((IList)paired.Device.Permissions)[0] = RemotePermissions.Streaming);
+ Assert.True(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Status));
+ Assert.False(registry.Allows(paired.Device.Id, paired.Token, RemotePermissions.Streaming));
+ }
+
+ [Theory]
+ [InlineData(null)][InlineData("")][InlineData("invalid")]
+ [InlineData("0000000000000000000000000000000000000000000000000000000000000000")]
+ public void BadTokensCannotAuthenticate(string? token)
+ {
+ var registry = new RemoteDeviceRegistry();
+ var paired = Pair(registry, RemotePermissions.Status);
+ Assert.False(registry.Allows(paired.Device.Id, token, RemotePermissions.Status));
+ Assert.False(registry.Allows("unknown", paired.Token, RemotePermissions.Status));
+ Assert.False(registry.Allows(null, paired.Token, RemotePermissions.Status));
+ }
+
+ [Theory]
+ [InlineData("powerpoint", "next", RemotePermissions.PowerPoint)]
+ [InlineData("powerpoint", "previous", RemotePermissions.PowerPoint)]
+ [InlineData("powerpoint", "goto", RemotePermissions.PowerPoint)]
+ [InlineData("powerpoint", "black", RemotePermissions.PowerPoint)]
+ [InlineData("powerpoint", "resume", RemotePermissions.PowerPoint)]
+ [InlineData("obs", "scene.switch", RemotePermissions.Scenes)]
+ [InlineData("obs", "record.start", RemotePermissions.Recording)]
+ [InlineData("obs", "record.stop", RemotePermissions.Recording)]
+ [InlineData("obs", "stream.start", RemotePermissions.Streaming)]
+ [InlineData("obs", "stream.stop", RemotePermissions.Streaming)]
+ [InlineData("obs", "input.mute", RemotePermissions.Audio)]
+ public async Task CommandsRequireTheirSpecificOwnerGrantedPermission(string plugin, string action, string permission)
+ {
+ var registry = new RemoteDeviceRegistry();
+ var target = new RecordingPlugin(plugin, action);
+ var gateway = new RemoteCommandGateway(registry, new CommandDispatcher([target]));
+ var readOnly = Pair(registry, RemotePermissions.Status);
+ var authorized = Pair(registry, permission);
+ var command = DispatcherTests.Command(plugin, action);
+ var denied = await gateway.DispatchAsync(readOnly.Device.Id, readOnly.Token, command);
+ Assert.Equal("access_denied", denied.Code);
+ Assert.False(denied.Success);
+ Assert.Equal(0, target.Calls);
+ Assert.True((await gateway.DispatchAsync(authorized.Device.Id, authorized.Token, command)).Success);
+ Assert.Equal(1, target.Calls);
+ }
+
+ [Theory]
+ [InlineData("powerpoint", "save")][InlineData("powerpoint", "open")]
+ [InlineData("powerpoint", "NEXT")][InlineData("obs", "request")]
+ [InlineData("androidremote", "pair")][InlineData("other", "next")]
+ public async Task UnknownActionsRemainDeniedEvenWithEveryRemotePermission(string plugin, string action)
+ {
+ var registry = new RemoteDeviceRegistry();
+ var paired = Pair(registry, RemotePermissions.All.ToArray());
+ var target = new RecordingPlugin(plugin, action);
+ var gateway = new RemoteCommandGateway(registry, new CommandDispatcher([target]));
+ Assert.Equal("access_denied", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, DispatcherTests.Command(plugin, action))).Code);
+ Assert.Equal(0, target.Calls);
+ }
+
+ [Fact]
+ public async Task DuplicateResultsAreIsolatedByPairingAndPreserveClientCorrelation()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var first = Pair(registry, RemotePermissions.PowerPoint);
+ var second = Pair(registry, RemotePermissions.PowerPoint);
+ var target = new RecordingPlugin();
+ var dispatcher = new CommandDispatcher([target]);
+ var gateway = new RemoteCommandGateway(registry, dispatcher);
+ var command = DispatcherTests.Command("powerpoint", "next");
+ await dispatcher.DispatchAsync(command);
+ var results = await Task.WhenAll(Enumerable.Range(0, 10)
+ .Select(_ => gateway.DispatchAsync(first.Device.Id, first.Token, command)));
+ Assert.All(results, r => { Assert.True(r.Success); Assert.Equal(command.Id, r.Id); });
+ Assert.Equal(2, target.Calls); // Lokalt + første enhed / Local + first device.
+ var uppercase = command with { Id = command.Id.ToUpperInvariant() };
+ Assert.Equal(uppercase.Id, (await gateway.DispatchAsync(first.Device.Id, first.Token, uppercase)).Id);
+ Assert.Equal("id_conflict", (await gateway.DispatchAsync(first.Device.Id, first.Token,
+ command with { Arguments = Wire.Data(new { changed = true }) })).Code);
+ Assert.True((await gateway.DispatchAsync(second.Device.Id, second.Token, command)).Success);
+ Assert.Equal(3, target.Calls);
+ registry.RevokeDevice(first.Device.Id);
+ Assert.Equal("access_denied", (await gateway.DispatchAsync(first.Device.Id, first.Token, command)).Code);
+ Assert.Equal(3, target.Calls);
+ }
+
+ [Theory]
+ [InlineData(false)][InlineData(true)]
+ public async Task RevokedOrExpiredDeviceCannotExecuteAfterWaitingBehindLocalCommand(bool expire)
+ {
+ var clock = new TestClock();
+ var registry = new RemoteDeviceRegistry(clock);
+ var paired = Pair(registry, RemotePermissions.PowerPoint);
+ var target = new RecordingPlugin { BlockCommands = true };
+ var dispatcher = new CommandDispatcher([target]);
+ var local = dispatcher.DispatchAsync(DispatcherTests.Command("powerpoint", "next"));
+ await target.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ var gateway = new RemoteCommandGateway(registry, dispatcher);
+ var remote = gateway.DispatchAsync(paired.Device.Id, paired.Token, DispatcherTests.Command("powerpoint", "next"));
+ Assert.False(remote.IsCompleted);
+ if (expire) clock.Advance(RemoteDeviceRegistry.DeviceLifetime);
+ else registry.RevokeDevice(paired.Device.Id);
+ target.Release.TrySetResult();
+ Assert.True((await local).Success);
+ Assert.Equal("access_denied", (await remote).Code);
+ Assert.Equal(1, target.Calls);
+ }
+
+ [Fact]
+ public async Task TimeoutReturnsUnknownAndDoesNotReplayTheCommand()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var paired = Pair(registry, RemotePermissions.PowerPoint);
+ var target = new RecordingPlugin { BlockCommands = true };
+ var gateway = new RemoteCommandGateway(registry, new CommandDispatcher([target], TimeSpan.FromMilliseconds(100)));
+ var command = DispatcherTests.Command("powerpoint", "next");
+ Assert.Equal("outcome_unknown", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command)).Code);
+ Assert.Equal("outcome_unknown", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command)).Code);
+ Assert.Equal(1, target.Calls);
+ }
+
+ [Fact]
+ public async Task CoreValidationAndCancellationStillApplyToAuthorizedDevices()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var paired = Pair(registry, RemotePermissions.PowerPoint);
+ var target = new RecordingPlugin();
+ var gateway = new RemoteCommandGateway(registry, new CommandDispatcher([target]));
+ var command = DispatcherTests.Command("powerpoint", "next");
+ Assert.Equal("invalid_command", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command with { Id = "bad" })).Code);
+ Assert.Equal("unsupported_protocol", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command with { ProtocolVersion = "2" })).Code);
+ Assert.Equal("invalid_command", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command with { Arguments = default })).Code);
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+ Assert.Equal("cancelled_before_dispatch", (await gateway.DispatchAsync(paired.Device.Id, paired.Token, command, cancelled.Token)).Code);
+ Assert.Equal(0, target.Calls);
+ }
+
+ [Fact]
+ public async Task StatusNeedsItsOwnPermissionAndRechecksRevocationAfterReading()
+ {
+ var registry = new RemoteDeviceRegistry();
+ var slidesOnly = Pair(registry, RemotePermissions.PowerPoint);
+ var reader = Pair(registry, RemotePermissions.Status);
+ var target = new RecordingPlugin { BlockStatus = true };
+ var gateway = new RemoteCommandGateway(registry, new CommandDispatcher([target]));
+ Assert.False((await gateway.GetStatusAsync(slidesOnly.Device.Id, slidesOnly.Token)).Success);
+ Assert.Equal(0, target.StatusCalls);
+ var reading = gateway.GetStatusAsync(reader.Device.Id, reader.Token);
+ await target.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ registry.RevokeDevice(reader.Device.Id);
+ target.Release.TrySetResult();
+ var denied = await reading;
+ Assert.False(denied.Success);
+ Assert.Null(denied.Status);
+ var next = Pair(registry, RemotePermissions.Status);
+ var status = await gateway.GetStatusAsync(next.Device.Id, next.Token);
+ Assert.True(status.Success);
+ Assert.Equal("ready", status.Status!.Plugins.Single().State);
+ Assert.DoesNotContain(next.Token, JsonSerializer.Serialize(status, Wire.Json));
+ }
+
+ [Fact]
+ public async Task CatalogNeverClaimsThatThePhoneTransportIsReady()
+ {
+ await using var plugin = new AndroidRemotePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ Assert.Empty(plugin.Descriptor.Actions);
+ Assert.Equal("development", plugin.Descriptor.Maturity);
+ var status = (await dispatcher.GetStatusAsync()).Plugins.Single();
+ Assert.Equal("unavailable", status.State);
+ Assert.Equal("transport_not_configured", status.Data!.Value.GetProperty("reason").GetString());
+ Assert.NotEqual(status.Message.Da, status.Message.En);
+ Assert.False((await dispatcher.DispatchAsync(DispatcherTests.Command("androidremote", "pair"))).Success);
+ }
+
+ private static DeviceCredential Pair(RemoteDeviceRegistry registry, params string[] permissions)
+ {
+ var offer = registry.BeginPairing("Test phone", permissions);
+ return Assert.IsType(registry.CompletePairing(offer.Id, offer.Secret));
+ }
+
+ private sealed class TestClock : TimeProvider
+ {
+ private long timestamp;
+ public DateTimeOffset Utc = new(2026, 11, 1, 12, 0, 0, TimeSpan.Zero);
+ public override DateTimeOffset GetUtcNow() => Utc;
+ public override long GetTimestamp() => timestamp;
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+ public void Advance(TimeSpan elapsed) { timestamp += elapsed.Ticks; Utc += elapsed; }
+ }
+
+ private sealed class RecordingPlugin(string id = "powerpoint", string action = "next") : IHubPlugin
+ {
+ public int Calls;
+ public int StatusCalls;
+ public bool BlockCommands;
+ public bool BlockStatus;
+ public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public PluginDescriptor Descriptor { get; } = new(id, new("Test", "Test"), "test", [action]);
+ public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken)
+ {
+ Interlocked.Increment(ref Calls);
+ Entered.TrySetResult();
+ if (BlockCommands) await Release.Task.WaitAsync(cancellationToken);
+ return Wire.Result(command, true, "ok", "Bekræftet.", "Confirmed.");
+ }
+ public async ValueTask GetStatusAsync(CancellationToken cancellationToken)
+ {
+ Interlocked.Increment(ref StatusCalls);
+ Entered.TrySetResult();
+ if (BlockStatus) await Release.Task.WaitAsync(cancellationToken);
+ return new(Descriptor.Id, "ready", new("Klar.", "Ready."));
+ }
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+}
diff --git a/tests/ControlHub.Tests/ControlHub.Tests.csproj b/tests/ControlHub.Tests/ControlHub.Tests.csproj
new file mode 100644
index 0000000..d07dd65
--- /dev/null
+++ b/tests/ControlHub.Tests/ControlHub.Tests.csproj
@@ -0,0 +1,14 @@
+
+ false true
+
+
+
+
+ all
+
+
+
+
+
+
+
diff --git a/tests/ControlHub.Tests/DispatcherTests.cs b/tests/ControlHub.Tests/DispatcherTests.cs
new file mode 100644
index 0000000..b356c8a
--- /dev/null
+++ b/tests/ControlHub.Tests/DispatcherTests.cs
@@ -0,0 +1,125 @@
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Core;
+using Xunit;
+
+namespace ControlHub.Tests;
+
+public sealed class DispatcherTests
+{
+ internal static Command Command(string plugin = "fake", string action = "run", object? args = null)
+ => new("1", Guid.NewGuid().ToString("D"), plugin, action, Wire.Data(args ?? new { }));
+
+ [Fact]
+ public async Task ConcurrentRetriesExecuteOnlyOnce()
+ {
+ var plugin = new FakePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ var command = Command();
+ var results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => dispatcher.DispatchAsync(command)));
+ Assert.Equal(1, plugin.Calls);
+ Assert.All(results, r => Assert.True(r.Success));
+ Assert.All(results, r => Assert.Equal(command.Id, r.Id));
+ }
+
+ [Fact]
+ public async Task SameIdWithDifferentPayloadIsRejected()
+ {
+ var plugin = new FakePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ var command = Command();
+ await dispatcher.DispatchAsync(command);
+ var result = await dispatcher.DispatchAsync(command with { Arguments = Wire.Data(new { other = true }) });
+ Assert.Equal("id_conflict", result.Code);
+ Assert.Equal(1, plugin.Calls);
+ }
+
+ [Theory]
+ [InlineData("2", "fake", "run", "unsupported_protocol")]
+ [InlineData("1", "missing", "run", "unknown_plugin")]
+ [InlineData("1", "fake", "save", "unsupported_action")]
+ public async Task InvalidRoutesNeverReachPlugin(string protocol, string pluginId, string action, string expected)
+ {
+ var plugin = new FakePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ var result = await dispatcher.DispatchAsync(Command(pluginId, action) with { ProtocolVersion = protocol });
+ Assert.Equal(expected, result.Code);
+ Assert.Equal(0, plugin.Calls);
+ }
+
+ [Fact]
+ public async Task InvalidEnvelopeNeverReachesPlugin()
+ {
+ var plugin = new FakePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ Assert.Equal("invalid_command", (await dispatcher.DispatchAsync(Command() with { Id = "not-a-uuid" })).Code);
+ Assert.Equal("invalid_command", (await dispatcher.DispatchAsync(Command() with { Arguments = default })).Code);
+ Assert.Equal(0, plugin.Calls);
+ }
+
+ [Fact]
+ public async Task TimeoutIsUnknownAndNotAutomaticallyRetried()
+ {
+ var plugin = new FakePlugin { WaitUntilCancelled = true };
+ var dispatcher = new CommandDispatcher([plugin], TimeSpan.FromMilliseconds(50));
+ var command = Command();
+ Assert.Equal("outcome_unknown", (await dispatcher.DispatchAsync(command)).Code);
+ Assert.Equal("outcome_unknown", (await dispatcher.DispatchAsync(command)).Code);
+ Assert.Equal(1, plugin.Calls);
+ }
+
+ [Fact]
+ public async Task CancelledBeforeDispatchNeverExecutes()
+ {
+ var plugin = new FakePlugin();
+ var dispatcher = new CommandDispatcher([plugin]);
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+ Assert.Equal("cancelled_before_dispatch", (await dispatcher.DispatchAsync(Command(), cancelled.Token)).Code);
+ Assert.Equal(0, plugin.Calls);
+ }
+
+ [Fact]
+ public async Task PluginFaultDoesNotExposeExceptionOrBreakStatus()
+ {
+ var plugin = new FakePlugin { Fail = true };
+ var dispatcher = new CommandDispatcher([plugin]);
+ var result = await dispatcher.DispatchAsync(Command());
+ Assert.Equal("plugin_error", result.Code);
+ Assert.DoesNotContain("secret", JsonSerializer.Serialize(result, Wire.Json));
+ Assert.Equal("unavailable", (await dispatcher.GetStatusAsync()).Plugins.Single().State);
+ }
+
+ [Fact]
+ public void WireRoundTripsAndRejectsUnknownFields()
+ {
+ var command = Command("obs", "scene.switch", new { sceneName = "Scene A" });
+ var json = JsonSerializer.Serialize(command, Wire.Json);
+ Assert.Contains("\"protocolVersion\"", json);
+ Assert.Equal("scene.switch", JsonSerializer.Deserialize(json, Wire.Json)!.Action);
+ Assert.Throws(() => JsonSerializer.Deserialize(json[..^1] + ",\"extra\":true}", Wire.Json));
+ }
+
+ [Fact]
+ public void DuplicatePluginIdsFailAtStartup()
+ => Assert.Throws(() => new CommandDispatcher([new FakePlugin(), new FakePlugin()]));
+
+ private sealed class FakePlugin : IHubPlugin
+ {
+ public int Calls;
+ public bool Fail { get; init; }
+ public bool WaitUntilCancelled { get; init; }
+ public PluginDescriptor Descriptor { get; } = new("fake", new("Test", "Test"), "test", ["run"]);
+ public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken)
+ {
+ Interlocked.Increment(ref Calls);
+ if (Fail) throw new InvalidOperationException("secret");
+ if (WaitUntilCancelled) await Task.Delay(Timeout.Infinite, cancellationToken);
+ await Task.Yield();
+ return Wire.Result(command, true, "ok", "OK", "OK");
+ }
+ public ValueTask GetStatusAsync(CancellationToken cancellationToken)
+ => Fail ? throw new InvalidOperationException("secret") : ValueTask.FromResult(new PluginStatus("fake", "ready", new("OK", "OK")));
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+}
diff --git a/tests/ControlHub.Tests/ObsTransportTests.cs b/tests/ControlHub.Tests/ObsTransportTests.cs
new file mode 100644
index 0000000..eaf2fa4
--- /dev/null
+++ b/tests/ControlHub.Tests/ObsTransportTests.cs
@@ -0,0 +1,182 @@
+using System.Net;
+using System.Net.WebSockets;
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Plugins.Obs;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using Xunit;
+
+namespace ControlHub.Tests;
+
+public sealed class ObsTransportTests
+{
+ [Theory]
+ [InlineData(false)][InlineData(true)]
+ public async Task HandshakeAuthenticationFragmentsAndResponseWork(bool authenticated)
+ {
+ await using var server = await FakeServer.StartAsync(authenticated);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ var data = await new ObsClient(server.Endpoint, authenticated ? "password" : null)
+ .RequestAsync("GetCurrentProgramScene", new { }, timeout.Token);
+ Assert.Equal("Main", data!.Value.GetProperty("currentProgramSceneName").GetString());
+ Assert.Equal("GetCurrentProgramScene", await server.Request.Task.WaitAsync(timeout.Token));
+ }
+
+ [Theory]
+ [InlineData(true, false)][InlineData(false, true)]
+ public async Task RejectsFailedRequestsAndMismatchedCorrelation(bool reject, bool wrongId)
+ {
+ await using var server = await FakeServer.StartAsync(false, reject, wrongId);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ var error = await Assert.ThrowsAsync(() =>
+ new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token));
+ Assert.Equal(wrongId, error.OutcomeUnknown);
+ Assert.Equal(wrongId ? ObsFailure.ProtocolError : ObsFailure.RequestRejected, error.Reason);
+ }
+
+ [Fact]
+ public async Task MissingPasswordFailsBeforeSendingCommand()
+ {
+ await using var server = await FakeServer.StartAsync(true);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ var error = await Assert.ThrowsAsync(() =>
+ new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token));
+ Assert.Equal(ObsFailure.PasswordMissing, error.Reason);
+ Assert.False(error.OutcomeUnknown);
+ Assert.False(server.Request.Task.IsCompleted);
+ }
+
+ [Fact]
+ public async Task WrongPasswordCloseIsIdentifiedWithoutSendingCommandOrLeakingServerText()
+ {
+ await using var server = await FakeServer.StartAsync(true, authenticationFailure: true);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ await using var plugin = new ObsPlugin(new ObsClient(server.Endpoint, "wrong-secret"));
+ var status = await plugin.GetStatusAsync(timeout.Token);
+ Assert.Equal("authentication_failed", status.Data!.Value.GetProperty("reason").GetString());
+ Assert.Contains("adgangskoden", status.Message.Da);
+ Assert.Contains("password", status.Message.En);
+ Assert.DoesNotContain("private-server-detail", JsonSerializer.Serialize(status));
+ Assert.DoesNotContain("wrong-secret", JsonSerializer.Serialize(status));
+ Assert.False(server.Request.Task.IsCompleted);
+ }
+
+ [Fact]
+ public async Task ClosedPortHasConnectionGuidanceAndNoCommandWasSent()
+ {
+ // Reserve a port with no listener; avoid a fixed port or a release/rebind race.
+ using var port = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
+ System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
+ port.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+ var endpoint = new Uri($"ws://127.0.0.1:{((IPEndPoint)port.LocalEndPoint!).Port}");
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ var error = await Assert.ThrowsAsync(() =>
+ new ObsClient(endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token));
+ Assert.Equal(ObsFailure.ConnectionUnavailable, error.Reason);
+ Assert.False(error.OutcomeUnknown);
+ }
+
+ [Fact]
+ public async Task DisconnectAfterRequestReportsUnknownOutcomeRatherThanRejection()
+ {
+ await using var server = await FakeServer.StartAsync(false, closeAfterRequest: true);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ await using var plugin = new ObsPlugin(new ObsClient(server.Endpoint, null));
+ var result = await plugin.ExecuteAsync(DispatcherTests.Command("obs", "record.start"), timeout.Token);
+ Assert.Equal("outcome_unknown", result.Code);
+ Assert.False(result.Success);
+ Assert.Equal("StartRecord", await server.Request.Task.WaitAsync(timeout.Token));
+ Assert.Equal("connection_lost", result.Data!.Value.GetProperty("reason").GetString());
+ }
+
+ [Fact]
+ public async Task MalformedHandshakeHasProtocolGuidanceAndSendsNoCommand()
+ {
+ await using var server = await FakeServer.StartAsync(true, malformedHello: true);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ var error = await Assert.ThrowsAsync(() =>
+ new ObsClient(server.Endpoint, "password").RequestAsync("StartRecord", new { }, timeout.Token));
+ Assert.Equal(ObsFailure.ProtocolError, error.Reason);
+ Assert.False(error.OutcomeUnknown);
+ Assert.False(server.Request.Task.IsCompleted);
+ }
+
+ private sealed class FakeServer(WebApplication app) : IAsyncDisposable
+ {
+ public Uri Endpoint => new(app.Urls.Single().Replace("http://", "ws://", StringComparison.Ordinal));
+ public TaskCompletionSource Request { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public static async Task StartAsync(bool authenticated, bool reject = false, bool wrongId = false,
+ bool authenticationFailure = false, bool closeAfterRequest = false, bool malformedHello = false)
+ {
+ var builder = WebApplication.CreateBuilder();
+ builder.Logging.ClearProviders();
+ builder.WebHost.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
+ var app = builder.Build();
+ var server = new FakeServer(app);
+ app.UseWebSockets();
+ app.Map("/", async context =>
+ {
+ using var socket = await context.WebSockets.AcceptWebSocketAsync();
+ var ct = context.RequestAborted;
+ try
+ {
+ if (malformedHello)
+ {
+ await Send(socket, new { op = 0, d = new { authentication = new { salt = "salt" } } }, ct);
+ await Read(socket, ct);
+ return;
+ }
+ await Send(socket, new { op = 0, d = authenticated ?
+ Wire.Data(new { rpcVersion = 1, authentication = new { salt = "salt", challenge = "challenge" } }) :
+ Wire.Data(new { rpcVersion = 1 }) }, ct);
+ var identify = await Read(socket, ct);
+ Assert.Equal(1, identify.GetProperty("op").GetInt32());
+ if (authenticationFailure)
+ {
+ await socket.CloseOutputAsync((WebSocketCloseStatus)4009, "private-server-detail", ct);
+ return;
+ }
+ if (authenticated) Assert.Equal(ObsClient.Authenticate("password", "salt", "challenge"), identify.GetProperty("d").GetProperty("authentication").GetString());
+ await Send(socket, new { op = 2, d = new { negotiatedRpcVersion = 1 } }, ct);
+ var request = (await Read(socket, ct)).GetProperty("d");
+ var requestType = request.GetProperty("requestType").GetString()!;
+ server.Request.TrySetResult(requestType);
+ if (closeAfterRequest)
+ {
+ await socket.CloseOutputAsync(WebSocketCloseStatus.InternalServerError, "private-server-detail", ct);
+ return;
+ }
+ await Send(socket, new { op = 5, d = new { eventType = "IgnoredEvent" } }, ct);
+ await Send(socket, new { op = 7, d = new {
+ requestType, requestId = wrongId ? "wrong" : request.GetProperty("requestId").GetString(),
+ requestStatus = new { result = !reject, code = reject ? 500 : 100 },
+ responseData = new { currentProgramSceneName = "Main" }
+ } }, ct);
+ }
+ catch (WebSocketException) { }
+ catch (OperationCanceledException) { }
+ });
+ await app.StartAsync();
+ return server;
+ }
+ private static async Task Send(WebSocket socket, object data, CancellationToken ct)
+ {
+ var bytes = JsonSerializer.SerializeToUtf8Bytes(data, Wire.Json);
+ var split = bytes.Length / 2;
+ await socket.SendAsync(new ArraySegment(bytes, 0, split), WebSocketMessageType.Text, false, ct);
+ await socket.SendAsync(new ArraySegment(bytes, split, bytes.Length - split), WebSocketMessageType.Text, true, ct);
+ }
+ private static async Task Read(WebSocket socket, CancellationToken ct)
+ {
+ var bytes = new byte[8192];
+ var result = await socket.ReceiveAsync(new ArraySegment(bytes), ct);
+ if (result.MessageType == WebSocketMessageType.Close) throw new WebSocketException();
+ using var doc = JsonDocument.Parse(bytes.AsMemory(0, result.Count));
+ return doc.RootElement.Clone();
+ }
+ public async ValueTask DisposeAsync() { await app.StopAsync(); await app.DisposeAsync(); }
+ }
+}
diff --git a/tests/ControlHub.Tests/PluginTests.cs b/tests/ControlHub.Tests/PluginTests.cs
new file mode 100644
index 0000000..27e4682
--- /dev/null
+++ b/tests/ControlHub.Tests/PluginTests.cs
@@ -0,0 +1,150 @@
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Plugins.Obs;
+using ControlHub.Plugins.Planned;
+using ControlHub.Plugins.PowerPoint;
+using Xunit;
+
+namespace ControlHub.Tests;
+
+public sealed class PluginTests
+{
+ [Theory]
+ [InlineData("next")][InlineData("previous")][InlineData("black")][InlineData("resume")]
+ public async Task PowerPointRoutesOnlySlideshowOperations(string action)
+ {
+ var session = new FakeSlideShow();
+ await using var plugin = new PowerPointPlugin(session);
+ Assert.True((await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", action), default)).Success);
+ Assert.Equal(action, session.Action);
+ }
+
+ [Theory]
+ [InlineData("{}")][InlineData("{\"slide\":0}")][InlineData("{\"slide\":-1}")]
+ [InlineData("{\"slide\":1.5}")][InlineData("{\"slide\":\"2\"}")]
+ [InlineData("{\"slide\":1,\"path\":\"x.pptx\"}")]
+ [InlineData("{\"slide\":1,\"slide\":2}")]
+ public async Task InvalidGoToNeverCallsPowerPoint(string args)
+ {
+ var session = new FakeSlideShow();
+ await using var plugin = new PowerPointPlugin(session);
+ using var document = JsonDocument.Parse(args);
+ var result = await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", "goto") with { Arguments = document.RootElement.Clone() }, default);
+ Assert.Equal("invalid_arguments", result.Code);
+ Assert.Null(session.Action);
+ }
+
+ [Fact]
+ public async Task GoToAndStatusUseSessionAndSurfaceUnavailability()
+ {
+ var session = new FakeSlideShow();
+ await using var plugin = new PowerPointPlugin(session);
+ Assert.True((await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", "goto", new { slide = 3 }), default)).Success);
+ Assert.Equal(3, session.Slide);
+ Assert.Equal("ready", (await plugin.GetStatusAsync(default)).State);
+ session.Unavailable = true;
+ Assert.Equal("slideshow_unavailable", (await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", "next"), default)).Code);
+ Assert.Equal("unavailable", (await plugin.GetStatusAsync(default)).State);
+ }
+
+ [Theory]
+ [InlineData(SlideShowFailure.NotRegistered, "powerpoint_not_found")]
+ [InlineData(SlideShowFailure.NoSlideshow, "no_slideshow")]
+ [InlineData(SlideShowFailure.MultipleSlideshows, "multiple_slideshows")]
+ [InlineData(SlideShowFailure.ConnectionUnavailable, "powerpoint_unavailable")]
+ public async Task PowerPointFailureReasonIsPreservedInStatusAndCommands(SlideShowFailure reason, string code)
+ {
+ var session = new FakeSlideShow { Unavailable = true, FailureReason = reason };
+ await using var plugin = new PowerPointPlugin(session);
+ var status = await plugin.GetStatusAsync(default);
+ var command = await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", "next"), default);
+ Assert.Equal("unavailable", status.State);
+ Assert.Equal(code, status.Data!.Value.GetProperty("reason").GetString());
+ Assert.Equal(code, command.Data!.Value.GetProperty("reason").GetString());
+ Assert.Equal(status.Message, command.Message);
+ Assert.NotEqual(status.Message.Da, status.Message.En);
+ Assert.False(command.Success);
+ Assert.Null(session.Action);
+ }
+
+ [Theory]
+ [InlineData("save")][InlineData("open")][InlineData("edit")][InlineData("close")]
+ public async Task PresentationFileOperationsAreNotSupported(string action)
+ {
+ var session = new FakeSlideShow();
+ await using var plugin = new PowerPointPlugin(session);
+ Assert.Equal("unsupported_action", (await plugin.ExecuteAsync(DispatcherTests.Command("powerpoint", action), default)).Code);
+ Assert.Null(session.Action);
+ }
+
+ [Theory]
+ [InlineData("record.start", "StartRecord")][InlineData("record.stop", "StopRecord")]
+ [InlineData("stream.start", "StartStream")][InlineData("stream.stop", "StopStream")]
+ public async Task ObsActionsMapToExplicitRequests(string action, string request)
+ {
+ var client = new FakeObsClient();
+ await using var plugin = new ObsPlugin(client);
+ Assert.True((await plugin.ExecuteAsync(DispatcherTests.Command("obs", action), default)).Success);
+ Assert.Equal(request, client.Request);
+ }
+
+ [Fact]
+ public async Task ObsSceneAndMuteValidateAndMapArguments()
+ {
+ var client = new FakeObsClient();
+ await using var plugin = new ObsPlugin(client);
+ Assert.Equal("invalid_arguments", (await plugin.ExecuteAsync(DispatcherTests.Command("obs", "scene.switch", new { sceneName = "" }), default)).Code);
+ Assert.Null(client.Request);
+ Assert.True((await plugin.ExecuteAsync(DispatcherTests.Command("obs", "scene.switch", new { sceneName = "Main" }), default)).Success);
+ Assert.Equal("SetCurrentProgramScene", client.Request);
+ Assert.Equal("Main", client.Data.GetProperty("sceneName").GetString());
+ Assert.True((await plugin.ExecuteAsync(DispatcherTests.Command("obs", "input.mute", new { inputName = "Mic", muted = false }), default)).Success);
+ Assert.False(client.Data.GetProperty("inputMuted").GetBoolean());
+ }
+
+ [Fact]
+ public async Task PlannedIntegrationCannotPretendToExecute()
+ {
+ await using var plugin = new PlannedPlugin("audio", new("Lyd", "Audio"));
+ Assert.Empty(plugin.Descriptor.Actions);
+ Assert.Equal("not_implemented", (await plugin.GetStatusAsync(default)).State);
+ Assert.False((await plugin.ExecuteAsync(DispatcherTests.Command("audio"), default)).Success);
+ }
+
+ [Theory]
+ [InlineData("ws://192.168.1.2:4455")][InlineData("wss://127.0.0.1:4455")]
+ [InlineData("ws://user:secret@localhost:4455")][InlineData("ws://localhost:4455/path")]
+ public void ObsRejectsNonlocalOrAmbiguousEndpoints(string uri)
+ => Assert.Throws(() => new ObsClient(new Uri(uri), null));
+
+ [Fact]
+ public void ObsAuthenticationMatchesIndependentSha256Fixture()
+ => Assert.Equal("zTM5ki6L2vVvBQiTG9ckH1Lh64AbnCf6XZ226UmnkIA=",
+ ObsClient.Authenticate("password", "salt", "challenge"));
+
+ private sealed class FakeSlideShow : ISlideShowSession
+ {
+ public string? Action;
+ public int? Slide;
+ public bool Unavailable;
+ public SlideShowFailure FailureReason;
+ public Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken)
+ {
+ if (Unavailable) throw new SlideShowUnavailableException(FailureReason);
+ Action = action; Slide = slide; return Task.CompletedTask;
+ }
+ public Task ReadAsync(CancellationToken cancellationToken)
+ => Unavailable ? throw new SlideShowUnavailableException(FailureReason) : Task.FromResult(new SlideShowSnapshot(3, 10, 1));
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+ private sealed class FakeObsClient : IObsClient
+ {
+ public string? Request;
+ public JsonElement Data;
+ public Task RequestAsync(string requestType, object requestData, CancellationToken cancellationToken)
+ {
+ Request = requestType; Data = Wire.Data(requestData);
+ return Task.FromResult(null);
+ }
+ }
+}
diff --git a/tests/ControlHub.Tests/RemoteOwnerTests.cs b/tests/ControlHub.Tests/RemoteOwnerTests.cs
new file mode 100644
index 0000000..5390409
--- /dev/null
+++ b/tests/ControlHub.Tests/RemoteOwnerTests.cs
@@ -0,0 +1,62 @@
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Plugins.AndroidRemote;
+using Xunit;
+
+namespace ControlHub.Tests;
+
+public sealed class RemoteOwnerTests
+{
+ [Fact]
+ public void InvitationBecomesPairedDeviceWithoutRevealingEitherSecret()
+ {
+ var store = new RemoteDeviceRegistry();
+ var invite = store.BeginPairing("Test phone", [RemotePermissions.Scenes]);
+ var pending = Assert.Single(store.GetOwnerSnapshot().PendingPairings);
+ Assert.Equal(invite.Id, pending.Id);
+ Assert.Equal(invite.ExpiresAt, pending.ExpiresAt);
+ Assert.Equal(RemotePermissions.Scenes, Assert.Single(pending.Permissions));
+ var paired = store.CompletePairing(invite.Id, invite.Secret)!;
+ var snapshot = store.GetOwnerSnapshot();
+ Assert.Empty(snapshot.PendingPairings);
+ Assert.False(snapshot.TransportReady);
+ Assert.Equal(paired.Device.Id, Assert.Single(snapshot.Devices).Id);
+ var serialized = JsonSerializer.Serialize(snapshot, Wire.Json);
+ Assert.DoesNotContain(paired.Token, serialized);
+ Assert.DoesNotContain(invite.Secret, serialized);
+ store.RevokeDevice(paired.Device.Id);
+ Assert.Empty(store.GetOwnerSnapshot().Devices);
+ }
+
+ [Theory]
+ [InlineData("http://192.168.1.2/api/v1/androidremote/owner/")]
+ [InlineData("http://127.0.0.1/api/v1/commands")]
+ [InlineData("http://user@127.0.0.1/api/v1/androidremote/owner/")]
+ [InlineData("http://127.0.0.1/api/v1/androidremote/owner/?key=test")]
+ [InlineData("http://127.0.0.1/api/v1/androidremote/owner/#fragment")]
+ public void OwnerClientRefusesUnexpectedCredentialDestinations(string endpoint)
+ {
+ using var http = new HttpClient();
+ Assert.Throws(() => new RemoteOwnerClient(http, new Uri(endpoint), "test"));
+ }
+
+ [Fact]
+ public async Task LostInvitationResponseIsNotAutomaticallyRepeated()
+ {
+ using var handler = new LostResponse();
+ using var http = new HttpClient(handler);
+ var client = new RemoteOwnerClient(http, new Uri("http://127.0.0.1:5187/api/v1/androidremote/owner/"), "test");
+ await Assert.ThrowsAsync(() => client.BeginAsync("Phone", ["status.read"]));
+ Assert.Equal(1, handler.Posts);
+ }
+ private sealed class LostResponse : HttpMessageHandler
+ {
+ public int Posts;
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ Assert.Equal(HttpMethod.Post, request.Method);
+ Interlocked.Increment(ref Posts);
+ throw new HttpRequestException("Simulated lost response");
+ }
+ }
+}
diff --git a/tests/PhoneHarness/PhoneHarness.csproj b/tests/PhoneHarness/PhoneHarness.csproj
new file mode 100644
index 0000000..844c55d
--- /dev/null
+++ b/tests/PhoneHarness/PhoneHarness.csproj
@@ -0,0 +1,8 @@
+
+ Exe
+
+
+
+
+
+
diff --git a/tests/PhoneHarness/Program.cs b/tests/PhoneHarness/Program.cs
new file mode 100644
index 0000000..827b0f0
--- /dev/null
+++ b/tests/PhoneHarness/Program.cs
@@ -0,0 +1,66 @@
+using System.Net;
+using System.Text.Json;
+using ControlHub.Contracts;
+using ControlHub.Core;
+using ControlHub.Plugins.AndroidRemote;
+using ControlHub.Plugins.AndroidRemote.Host;
+using ControlHub.Plugins.PowerPoint;
+using ControlHub.Plugins.Obs;
+
+// The production adapters act on isolated fixtures. No Office, OBS or presentation file is opened.
+var slides = new TestShow();
+var obs = new TestObs();
+await using var ppt = new PowerPointPlugin(slides);
+await using var studio = new ObsPlugin(obs);
+var devices = new RemoteDeviceRegistry();
+await using var server = await PhoneServer.StartAsync(IPAddress.Loopback, 0, devices, new CommandDispatcher([ppt, studio]));
+while (await Console.In.ReadLineAsync() is string line)
+{
+ object response;
+ switch (line)
+ {
+ case "invite":
+ response = devices.BeginPairing("Android test", ["status.read", "powerpoint.control", "obs.scenes"]);
+ break;
+ case "counts":
+ response = new { slides = slides.Calls, scenes = obs.Switches, slide = slides.Position, scene = obs.Scene };
+ break;
+ case "revoke":
+ devices.RevokeAll();
+ response = new { revoked = true };
+ break;
+ default: return;
+ }
+ Console.WriteLine(JsonSerializer.Serialize(response, Wire.Json));
+}
+
+sealed class TestShow : ISlideShowSession
+{
+ public int Position = 1;
+ public int Calls;
+ public Task ApplyAsync(string action, int? slide, CancellationToken ct)
+ {
+ Position += action switch { "next" => 1, "previous" => -1, _ => throw new InvalidOperationException() };
+ Interlocked.Increment(ref Calls);
+ return Task.CompletedTask;
+ }
+ public Task ReadAsync(CancellationToken ct) => Task.FromResult(new SlideShowSnapshot(Position, 4, 1));
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+}
+
+sealed class TestObs : IObsClient
+{
+ public string Scene = "Slides";
+ public int Switches;
+ public Task RequestAsync(string type, object data, CancellationToken ct)
+ {
+ if (type == "SetCurrentProgramScene")
+ {
+ Scene = Wire.Data(data).GetProperty("sceneName").GetString()!;
+ Interlocked.Increment(ref Switches);
+ return Task.FromResult(null);
+ }
+ return Task.FromResult(type == "GetCurrentProgramScene" ? Wire.Data(new { currentProgramSceneName = Scene })
+ : Wire.Data(new { outputActive = false }));
+ }
+}
diff --git a/tests/android-ui/AndroidManifest.xml b/tests/android-ui/AndroidManifest.xml
new file mode 100644
index 0000000..86ea60d
--- /dev/null
+++ b/tests/android-ui/AndroidManifest.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/tests/android-ui/run.py b/tests/android-ui/run.py
new file mode 100644
index 0000000..85243d1
--- /dev/null
+++ b/tests/android-ui/run.py
@@ -0,0 +1,73 @@
+"""Drive the actual APK against a loopback TLS fixture on an explicitly selected emulator."""
+import argparse
+import base64
+import json
+from pathlib import Path
+import subprocess
+
+root = Path(__file__).resolve().parents[2]
+parser = argparse.ArgumentParser()
+parser.add_argument("--serial", required=True)
+parser.add_argument("--adb", default="adb")
+parser.add_argument("--apk", required=True)
+parser.add_argument("--test-apk", required=True)
+args = parser.parse_args()
+if not args.serial.startswith("emulator-"):
+ raise SystemExit("Select a disposable emulator / Vælg en testemulator")
+
+
+def adb(*command):
+ result = subprocess.run([args.adb, "-s", args.serial, *command], capture_output=True, timeout=150)
+ if result.returncode:
+ raise RuntimeError("Emulator command failed: " + command[0])
+ return result.stdout.decode(errors="replace")
+
+
+def exchange(process, command):
+ process.stdin.write(command + "\n")
+ process.stdin.flush()
+ return json.loads(process.stdout.readline())
+
+
+if adb("shell", "getprop", "ro.kernel.qemu").strip() != "1":
+ raise SystemExit("Expected an emulator")
+subprocess.run(["dotnet", "build", "tests/PhoneHarness", "-c", "Release"], check=True, cwd=root)
+fixture = root / "tests/PhoneHarness/bin/Release/net10.0/PhoneHarness.dll"
+with subprocess.Popen(["dotnet", str(fixture)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as server:
+ port = None
+ try:
+ invite = exchange(server, "invite")
+ from urllib.parse import urlparse
+ port = str(urlparse(invite["transport"]["endpoint"]).port)
+ adb("reverse", "tcp:" + port, "tcp:" + port)
+ adb("install", "-r", args.apk)
+ adb("install", "-r", args.test_apk)
+ adb("shell", "pm", "clear", "dk.thebonden.controlhub.remote")
+ # Mint a fresh invitation after install, so slow package installation does not spend its lifetime.
+ invite = exchange(server, "invite")
+ encoded = base64.b64encode(json.dumps(invite).encode()).decode()
+ runner = "dk.thebonden.controlhub.remote.test/.PhoneTrial"
+ response = adb("shell", "am", "instrument", "-w", "-e", "invite", encoded, runner)
+ if "result=PASS" not in response:
+ raise RuntimeError(response.replace(encoded, "[invitation]"))
+ counts = exchange(server, "counts")
+ assert counts == {"slides": 2, "scenes": 1, "slide": 1, "scene": "Camera"}, counts
+ adb("reverse", "--remove", "tcp:" + port)
+ response = adb("shell", "am", "instrument", "-w", "-e", "phase", "offline", runner)
+ if "result=PASS" not in response:
+ raise RuntimeError(response)
+ adb("reverse", "tcp:" + port, "tcp:" + port)
+ response = adb("shell", "am", "instrument", "-w", "-e", "phase", "restored", runner)
+ if "result=PASS" not in response:
+ raise RuntimeError(response)
+ assert exchange(server, "counts") == counts
+ exchange(server, "revoke")
+ response = adb("shell", "am", "instrument", "-w", "-e", "phase", "revoked", runner)
+ if "result=PASS" not in response:
+ raise RuntimeError(response)
+ assert exchange(server, "counts") == counts
+ print("PASS: wrong certificate, pairing, next, previous, OBS scene, status, persistent session, revocation and exact action counts")
+ finally:
+ if port:
+ adb("reverse", "--remove", "tcp:" + port)
+ server.stdin.close()
diff --git a/tests/android-ui/src/PhoneTrial.java b/tests/android-ui/src/PhoneTrial.java
new file mode 100644
index 0000000..62400ad
--- /dev/null
+++ b/tests/android-ui/src/PhoneTrial.java
@@ -0,0 +1,75 @@
+package dk.thebonden.controlhub.remote.test;
+
+import android.app.*;
+import android.content.*;
+import android.os.Bundle;
+import android.util.Base64;
+import android.view.View;
+import android.widget.*;
+import java.util.concurrent.atomic.AtomicReference;
+import org.json.JSONObject;
+
+public final class PhoneTrial extends Instrumentation {
+ private Bundle args;
+ private Activity app;
+ private String step;
+ @Override public void onCreate(Bundle args) { this.args=args; start(); }
+ @Override public void onStart() {
+ Bundle result=new Bundle();
+ try {
+ Intent start=new Intent().setClassName("dk.thebonden.controlhub.remote","dk.thebonden.controlhub.remote.RemoteActivity");
+ start.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
+ app=startActivitySync(start);
+ if ("offline".equals(args.getString("phase"))) {
+ press("next"); expect("Outcome unknown");
+ } else if ("restored".equals(args.getString("phase"))) {
+ press("status"); expect("Slide 1 / 4"); expect("OBS · Camera");
+ } else if ("revoked".equals(args.getString("phase"))) {
+ press("status"); expect("Access expired or revoked"); exists("pair");
+ } else {
+ if ("English".equals(text("language"))) press("language");
+ String invitation=new String(Base64.decode(args.getString("invite"),Base64.DEFAULT),"UTF-8");
+ JSONObject bad=new JSONObject(invitation);
+ bad.getJSONObject("transport").put("certificateSha256",new String(new char[64]).replace('\0','0'));
+ enter("invitation",bad.toString()); press("pair"); expect("Secure connection failed");
+ enter("invitation",invitation); press("pair"); expect("Phone paired");
+ press("next"); expect("Confirmed."); press("status"); expect("Slide 2 / 4");
+ press("previous"); expect("Confirmed."); enter("scene","Camera"); press("switch"); expect("Confirmed.");
+ press("status"); expect("OBS · Camera"); expect("Slide 1 / 4");
+ }
+ result.putString("result","PASS");
+ finish(Activity.RESULT_OK,result);
+ } catch (Throwable error) {
+ result.putString("result","FAIL at " + step + " (" + error.getClass().getSimpleName() + ")");
+ finish(Activity.RESULT_CANCELED,result);
+ }
+ }
+ private View find(String tag) { return app.getWindow().getDecorView().findViewWithTag(tag); }
+ private void exists(String tag) {
+ final AtomicReference found=new AtomicReference<>();
+ runOnMainSync(() -> found.set(find(tag)));
+ if (found.get()==null) throw new AssertionError();
+ }
+ private void press(String tag) {
+ step="press "+tag;
+ runOnMainSync(() -> { View v=find(tag); if(v==null || !v.isEnabled()) return; v.performClick(); });
+ }
+ private void enter(String tag,String value) {
+ step="enter "+tag;
+ runOnMainSync(() -> ((EditText)find(tag)).setText(value));
+ }
+ private String text(String tag) {
+ AtomicReference value=new AtomicReference<>();
+ runOnMainSync(() -> value.set(((TextView)find(tag)).getText().toString()));
+ return value.get();
+ }
+ private void expect(String value) throws Exception {
+ step="expect "+value;
+ long end=android.os.SystemClock.elapsedRealtime()+40000;
+ while (android.os.SystemClock.elapsedRealtime() {
+ log = (log + d).slice(-4000);
+ const address = log.match(/Now listening on: http:\/\/127\.0\.0\.1:(\d+)/);
+ if (address) base = `http://127.0.0.1:${address[1]}/api/v1/`;
+});
+child.stderr.on("data", d => { log = (log + d).slice(-4000); });
+const headers = { Authorization:"Bearer " + token, "Content-Type":"application/json" };
+const post = body => fetch(base + "commands", {method:"POST",headers,body:JSON.stringify(body)});
+(async () => {
+ try {
+ let ready = false;
+ for(let i=0;i<100;i++) {
+ try { if(base && (await fetch(base+"plugins")).status===401) {ready=true;break;} } catch {}
+ if(child.exitCode !== null) throw new Error("Host exited: " + log);
+ await new Promise(resolve=>setTimeout(resolve,100));
+ }
+ assert.ok(ready, "Host did not start: " + log);
+ assert.equal((await fetch(base+"plugins",{headers:{Authorization:"Bearer wrong"}})).status,401);
+ assert.equal((await fetch(base+"plugins",{headers:{...headers,Origin:"https://example.com"}})).status,403);
+ const catalog = await (await fetch(base+"plugins",{headers})).json();
+ assert.ok(catalog.some(p=>p.id==="powerpoint"));
+ assert.ok(catalog.some(p=>p.id==="obs"));
+ await require('./remote-owner-smoke.cjs')(base, token, ownerKey);
+ assert.equal((await fetch(base+"commands",{method:"POST",headers,body:"{"})).status,400);
+ assert.equal((await fetch(base+"commands",{method:"POST",headers,body:"null"})).status,400);
+ const command={protocolVersion:"1",id:randomUUID(),plugin:"powerpoint",action:"save",arguments:{}};
+ assert.equal((await (await post(command)).json()).code,"unsupported_action");
+ command.protocolVersion="2";
+ assert.equal((await (await post(command)).json()).code,"unsupported_protocol");
+ command.protocolVersion="1"; command.action=null;
+ assert.equal((await (await post(command)).json()).code,"invalid_command");
+ const status=await (await fetch(base+"status",{headers})).json();
+ assert.equal(status.version,"0.0.001");
+ assert.equal(status.plugins.find(p=>p.id==="androidremote").state,"unavailable");
+ assert.equal(status.plugins.find(p=>p.id==="androidremote").data.reason,"transport_not_configured");
+ assert.deepEqual(catalog.find(p=>p.id==="androidremote").actions,[]);
+ assert.equal(status.plugins.find(p=>p.id==="obs").state,"unavailable");
+ const { createBridge } = require('../Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js');
+ const messages = [];
+ const bridge = createBridge(message => messages.push(message), (url, options) => {
+ assert.equal(url, 'http://127.0.0.1:5187/api/v1/status');
+ return fetch(base + 'status', options);
+ });
+ const action = 'dk.thebonden.controlhub.next';
+ await bridge.handle({event:'willAppear',context:'smoke-key',action,payload:{settings:{token}}});
+ await bridge.handle({event:'sendToPlugin',context:'smoke-key',action,
+ payload:{kind:'checkConnection',requestId:'smoke-check',token}});
+ assert.equal(messages.length,1);
+ assert.equal(messages[0].event,'sendToPropertyInspector');
+ assert.equal(messages[0].payload.requestId,'smoke-check');
+ assert.equal(messages[0].payload.code,'partial');
+ assert.equal(messages[0].payload.checks.find(p=>p.id==='obs').state,'unavailable');
+ assert.ok(!JSON.stringify(messages).includes(token));
+ console.log("Host and Stream Deck connection checks passed / Host- og Stream Deck-forbindelseskontrol bestået");
+ } finally { child.kill(); }
+})().catch(error=>{ console.error(error); process.exitCode=1; });
diff --git a/tests/inspector.test.cjs b/tests/inspector.test.cjs
new file mode 100644
index 0000000..ff2aa54
--- /dev/null
+++ b/tests/inspector.test.cjs
@@ -0,0 +1,81 @@
+const { test } = require("node:test");
+const assert = require("node:assert/strict");
+const vm = require("node:vm");
+const fs = require("node:fs");
+const path = require("node:path");
+const source = fs.readFileSync(path.join(__dirname,"../Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js"),"utf8");
+function inspector(language="da") {
+ const elements=new Map(),sent=[];
+ const el=id=>{if(!elements.has(id))elements.set(id,{value:"",textContent:"",disabled:false});return elements.get(id);};
+ let socket,timer;
+ class Socket {
+ static OPEN=1;
+ readyState=0;
+ constructor(){socket=this;}
+ send(message){sent.push(JSON.parse(message));}
+ }
+ const context=vm.createContext({document:{getElementById:el,documentElement:{}},WebSocket:Socket,
+ crypto:{randomUUID:()=>"request-1"},setTimeout:fn=>{timer=fn;return 1;},clearTimeout:()=>{timer=null;}});
+ vm.runInContext(source,context);
+ context.connectElgatoStreamDeckSocket(1234,"inspector-session","registerPropertyInspector","{}",JSON.stringify({
+ context:"key",action:"dk.thebonden.controlhub.next",payload:{settings:{language,token:"t".repeat(40)}}}));
+ socket.readyState=1;socket.onopen();
+ return {el,sent,socket,timeout:()=>timer?.()};
+}
+test("inspector connection check sends no command and does not save credentials",()=>{
+ const ui=inspector();
+ ui.el("token").value="new".repeat(20);
+ ui.el("check").onclick();
+ assert.deepEqual(ui.sent.map(m=>m.event),["registerPropertyInspector","sendToPlugin"]);
+ assert.equal(ui.sent[1].payload.kind,"checkConnection");
+ assert.equal(ui.sent[0].uuid,"inspector-session");
+ assert.equal(ui.sent[1].context,"inspector-session");
+ assert.equal(ui.sent[1].payload.token,"new".repeat(20));
+ assert.equal(ui.el("check").disabled,true);
+});
+test("distinct inspector registration and action contexts complete a real bridge round trip",async()=>{
+ const { createBridge }=require("../Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js");
+ const ui=inspector();
+ const bridge=createBridge(message=>ui.socket.onmessage({data:JSON.stringify(message)}),async()=>({ok:true,json:async()=>({
+ protocolVersion:"1",version:"0.0.001",plugins:[
+ {id:"powerpoint",state:"unavailable"},{id:"obs",state:"unavailable"}
+ ]
+ })}));
+ await bridge.handle({event:"willAppear",context:"key",action:"dk.thebonden.controlhub.next",payload:{settings:{}}});
+ ui.el("check").onclick();
+ const sent=ui.sent.at(-1);
+ assert.equal(sent.context,"inspector-session");
+ // Stream Deck validates the UI sender and forwards the action's key context.
+ await bridge.handle({...sent,context:"key"});
+ assert.equal(ui.el("check").disabled,false);
+ assert.match(ui.el("connection").textContent,/0\.0\.001/);
+ ui.el("save").onclick();
+ assert.equal(ui.sent.at(-1).event,"setSettings");
+ assert.equal(ui.sent.at(-1).action,"dk.thebonden.controlhub.next");
+ assert.equal(ui.sent.at(-1).context,"inspector-session");
+});
+test("inspector ignores mismatched results and shows matching bilingual result as text",()=>{
+ const ui=inspector("en");ui.el("check").onclick();
+ const payload={kind:"connectionResult",requestId:"wrong",message:{da:"Forbundet",en:"Connected"},checks:[]};
+ ui.socket.onmessage({data:JSON.stringify({event:"sendToPropertyInspector",context:"key",payload})});
+ assert.equal(ui.el("check").disabled,true);
+ payload.requestId="request-1";
+ payload.message.en="";
+ ui.socket.onmessage({data:JSON.stringify({event:"sendToPropertyInspector",context:"key",payload})});
+ assert.equal(ui.el("connection").textContent,"");
+ assert.equal(ui.el("check").disabled,false);
+ ui.el("language").value="da";ui.el("language").onchange();
+ assert.equal(ui.el("connection").textContent,"Forbundet");
+});
+test("editing token invalidates an outstanding diagnostic result",()=>{
+ const ui=inspector();ui.el("check").onclick();ui.el("token").oninput();
+ ui.socket.onmessage({data:JSON.stringify({event:"sendToPropertyInspector",context:"key",
+ payload:{kind:"connectionResult",requestId:"request-1",message:{da:"Old",en:"Old"},checks:[]}})});
+ assert.equal(ui.el("connection").textContent,"");
+});
+test("inspector timeout unlocks controls without sending another request",()=>{
+ const ui=inspector("en");ui.el("check").onclick();ui.timeout();
+ assert.equal(ui.el("check").disabled,false);
+ assert.match(ui.el("connection").textContent,/did not respond/);
+ assert.equal(ui.sent.length,2);
+});
diff --git a/tests/remote-owner-smoke.cjs b/tests/remote-owner-smoke.cjs
new file mode 100644
index 0000000..b02d0c1
--- /dev/null
+++ b/tests/remote-owner-smoke.cjs
@@ -0,0 +1,42 @@
+const assert = require('node:assert/strict');
+module.exports = async (base, token, ownerKey) => {
+ const root = base + 'androidremote/owner/';
+ const headers = { Authorization: 'Bearer ' + token, 'X-ControlHub-Owner': ownerKey, 'Content-Type': 'application/json' };
+ const request = (path = '', method = 'GET', body, h = headers) => fetch(root + path,
+ { method, headers: h, ...(body === undefined ? {} : { body }) });
+ const args = JSON.stringify({name: 'Smoke phone', permissions: ['status.read', 'obs.scenes']});
+ for (const [path, method, body] of [['', 'GET'], ['pairings','POST',args], ['access','DELETE']]) {
+ assert.equal((await request(path,method,body,{'X-ControlHub-Owner':ownerKey})).status,401);
+ assert.equal((await request(path,method,body,{Authorization:'Bearer '+token})).status,403);
+ assert.equal((await request(path,method,body,{...headers,'X-ControlHub-Owner':token})).status,403);
+ assert.equal((await request(path,method,body,{...headers,Origin:'https://example.com'})).status,403);
+ }
+ for (const bad of ['null', '{', '{"name":"a","name":"b","permissions":["status.read"]}',
+ '{"name":"a","permissions":[]}', '{"name":"a","permissions":["*"]}', '{"name":"a","permissions":[1]}',
+ '{"name":"a","permissions":["status.read"],"token":"x"}']) {
+ assert.equal((await request('pairings','POST',bad)).status,400);
+ }
+ assert.equal((await (await request()).json()).pendingPairings.length,0);
+ const response = await request('pairings','POST',args);
+ assert.equal(response.status,201);
+ assert.equal(response.headers.get('cache-control'),'no-store');
+ const offer = await response.json();
+ assert.ok(typeof offer.secret === 'string' && /^[A-F0-9]{64}$/.test(offer.secret));
+ const listed = await request();
+ assert.equal(listed.headers.get('cache-control'),'no-store');
+ const raw = await listed.text();
+ assert.ok(!raw.includes(offer.secret) && !raw.includes(ownerKey) && !raw.includes(token));
+ const view = JSON.parse(raw);
+ assert.equal(view.transportReady,false);
+ assert.equal(view.devices.length,0);
+ assert.equal(view.pendingPairings[0].id,offer.id);
+ assert.deepEqual(view.pendingPairings[0].permissions,['obs.scenes','status.read']);
+ assert.equal((await request('devices/'+offer.id,'DELETE')).status,404);
+ assert.equal((await request('pairings/'+offer.id,'DELETE')).status,204);
+ assert.equal((await request('pairings/'+offer.id,'DELETE')).status,404);
+ for (let i=0;i<8;i++) assert.equal((await request('pairings','POST',args)).status,201);
+ assert.equal((await request('pairings','POST',args)).status,409);
+ assert.equal((await request('access','DELETE')).status,204);
+ assert.equal((await (await request()).json()).pendingPairings.length,0);
+ assert.equal((await fetch(base+'androidremote/pair',{method:'POST',headers,body:args})).status,404);
+};
diff --git a/tests/streamdeck.test.cjs b/tests/streamdeck.test.cjs
new file mode 100644
index 0000000..c394064
--- /dev/null
+++ b/tests/streamdeck.test.cjs
@@ -0,0 +1,224 @@
+const { test } = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const pluginDir = path.join(__dirname, "../Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin");
+const { makeCommand, statusTitle, definitions } = require(path.join(pluginDir, "actions.js"));
+const { createBridge } = require(path.join(pluginDir, "bridge.js"));
+const prefix = "dk.thebonden.controlhub.";
+const token = "x".repeat(40);
+const appear = (action, settings = {}) => ({ event: "willAppear", context: "key", action: prefix + action, payload: { settings: { token, ...settings } } });
+
+test("all manifest actions map to implementations and assets exist", () => {
+ const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, "manifest.json")));
+ assert.equal(manifest.Actions.length, Object.keys(definitions).length);
+ for (const file of [manifest.CodePath, manifest.PropertyInspectorPath]) assert.ok(fs.existsSync(path.join(pluginDir, file)));
+ for (const action of manifest.Actions) {
+ assert.ok(definitions[action.UUID.slice(prefix.length)]);
+ for (const file of [action.Icon, action.States[0].Image]) assert.ok(fs.existsSync(path.join(pluginDir, file + ".svg")));
+ }
+});
+test("PowerPoint and OBS actions produce versioned commands", () => {
+ assert.equal(makeCommand(prefix+"next", {}, "id").action, "next");
+ assert.deepEqual(makeCommand(prefix+"scene", { sceneName: "Camera" }, "id").arguments, { sceneName: "Camera" });
+ assert.deepEqual(makeCommand(prefix+"mute", { inputName: "Mic", muted: false }, "id").arguments, { inputName: "Mic", muted: false });
+ assert.notEqual(makeCommand(prefix+"next", {}).id, makeCommand(prefix+"next", {}).id);
+});
+test("invalid settings never become commands", () => {
+ assert.throws(() => makeCommand(prefix+"goto", { slide: 1.5 }));
+ assert.throws(() => makeCommand(prefix+"goto", { slide: "" }));
+ assert.throws(() => makeCommand(prefix+"scene", {}));
+ assert.throws(() => makeCommand(prefix+"mute", { inputName: "Mic", muted: "false" }));
+ assert.throws(() => makeCommand("other.next", {}));
+ assert.throws(() => makeCommand(prefix+"status", {}));
+});
+test("keyDown dispatches once; keyUp does not dispatch", async () => {
+ const sent = [], calls = [];
+ const bridge = createBridge(m => sent.push(m), async (url, options) => {
+ calls.push({ url, options }); const cmd = JSON.parse(options.body);
+ return { ok: true, json: async () => ({ protocolVersion: "1", id: cmd.id, success: true }) };
+ });
+ await bridge.handle(appear("next"));
+ await bridge.handle({ event: "keyDown", context: "key" });
+ await bridge.handle({ event: "keyUp", context: "key" });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, "http://127.0.0.1:5187/api/v1/commands");
+ assert.equal(calls[0].options.headers.Authorization, "Bearer " + token);
+ assert.ok(sent.some(m => m.event === "showOk"));
+});
+test("overlapping presses are suppressed and failures are never retried", async () => {
+ let release, calls = 0; const sent = [];
+ const bridge = createBridge(m => sent.push(m), () => { calls++; return new Promise(resolve => { release = resolve; }); });
+ await bridge.handle(appear("recordstart"));
+ const first = bridge.handle({ event: "keyDown", context: "key" });
+ await bridge.handle({ event: "keyDown", context: "key" });
+ release({ ok: false });
+ await first;
+ assert.equal(calls, 1);
+ assert.ok(sent.some(m => m.event === "showAlert"));
+ assert.ok(!sent.some(m => m.event === "showOk"));
+});
+test("mismatched command response cannot show success", async () => {
+ const sent = [];
+ const bridge = createBridge(m => sent.push(m), async () => ({ ok: true, json: async () => ({ protocolVersion:"1", id:"wrong", success:true }) }));
+ await bridge.handle(appear("next"));
+ await bridge.handle({ event:"keyDown", context:"key" });
+ assert.ok(sent.some(m => m.event === "showAlert"));
+});
+test("status distinguishes unavailable devices and stopped outputs", () => {
+ const status = { protocolVersion:"1", plugins:[{ id:"powerpoint",state:"ready",data:{position:4} },
+ { id:"obs",state:"ready",data:{recording:{outputActive:false},streaming:{outputActive:true}} }] };
+ assert.equal(statusTitle(status,"en"), "PPT 4\nREC OFF\nLIVE ON");
+ status.plugins[1].state = "unavailable";
+ assert.equal(statusTitle(status,"da"), "PPT 4\nOPT ?\nLIVE ?");
+});
+test("missing token does not contact the host", async () => {
+ let calls = 0; const bridge = createBridge(() => {}, async () => { calls++; });
+ await bridge.handle(appear("next", { token:"" }));
+ await bridge.handle({ event:"keyDown",context:"key" });
+ assert.equal(calls,0);
+});
+test("hidden status keys stop polling", async () => {
+ let calls = 0;
+ const bridge = createBridge(() => {}, async () => { calls++; return {ok:true,json:async()=>({protocolVersion:"1",plugins:[]})}; });
+ await bridge.handle(appear("status"));
+ await bridge.handle({event:"willDisappear",context:"key"});
+ await bridge.poll();
+ assert.equal(calls,1);
+});
+
+const { connectionReport } = require(path.join(pluginDir, "diagnostics.js"));
+const statusFixture = () => ({ protocolVersion:"1",version:"0.0.001",plugins:[
+ {id:"powerpoint",state:"ready"},{id:"obs",state:"ready"}] });
+const checkMessage = (extra = {}) => ({event:"sendToPlugin",context:"key",action:prefix+"next",
+ payload:{kind:"checkConnection",requestId:"check-1",token,...extra}});
+test("main plugin icons are PNGs at both required resolutions", () => {
+ for(const [name,size] of [["plugin",28],["plugin@2x",56]]) {
+ const png=fs.readFileSync(path.join(pluginDir,"assets",name+".png"));
+ assert.equal(png.subarray(0,8).toString("hex"),"89504e470d0a1a0a");
+ assert.equal(png.readUInt32BE(16),size);
+ assert.equal(png.readUInt32BE(20),size);
+ }
+});
+test("connection check only reads status and does not persist or echo a token", async () => {
+ const sent=[],calls=[];
+ const bridge=createBridge(m=>sent.push(m),async(url,options)=>{
+ calls.push({url,options});return {ok:true,json:async()=>statusFixture()};
+ });
+ await bridge.handle(appear("next"));
+ await bridge.handle(checkMessage());
+ assert.equal(calls.length,1);
+ assert.ok(calls[0].url.endsWith("/status"));
+ assert.equal(calls[0].options.method,"GET");
+ assert.equal(calls[0].options.body,undefined);
+ assert.deepEqual(sent.map(m=>m.event),["sendToPropertyInspector"]);
+ assert.equal(sent[0].payload.code,"ready");
+ assert.equal(sent[0].payload.requestId,"check-1");
+ assert.ok(!JSON.stringify(sent).includes(token));
+});
+test("connection check distinguishes wrong token and busy host", async () => {
+ for(const [status,code] of [[401,"unauthorized"],[429,"busy"]]) {
+ const sent=[];
+ const bridge=createBridge(m=>sent.push(m),async()=>({ok:false,status,json:async()=>{throw new Error("must not read error body");}}));
+ await bridge.handle(appear("next"));
+ await bridge.handle(checkMessage());
+ assert.equal(sent[0].payload.code,code);
+ }
+});
+test("connection check rejects missing token before networking", async () => {
+ const sent=[];let calls=0;
+ const bridge=createBridge(m=>sent.push(m),async()=>{calls++;});
+ await bridge.handle(appear("next"));
+ await bridge.handle(checkMessage({token:""}));
+ assert.equal(calls,0);
+ assert.equal(sent[0].payload.code,"invalid_token");
+});
+test("connection check sanitizes transport exceptions", async () => {
+ const sent=[];
+ const bridge=createBridge(m=>sent.push(m),async()=>{throw new Error(token);});
+ await bridge.handle(appear("next"));
+ await bridge.handle(checkMessage());
+ assert.equal(sent[0].payload.code,"unreachable");
+ assert.ok(!JSON.stringify(sent).includes(token));
+});
+test("connection report distinguishes unavailable programs from a stopped host", () => {
+ const status=statusFixture();status.plugins[1].state="unavailable";
+ const report=connectionReport(status);
+ assert.equal(report.code,"partial");
+ assert.equal(report.checks[0].state,"ready");
+ assert.equal(report.checks[1].state,"unavailable");
+ assert.ok(report.message.da && report.message.en);
+});
+test("malformed or duplicate status cannot claim connectivity", () => {
+ assert.equal(connectionReport({}).code,"invalid_response");
+ const status=statusFixture();status.plugins.push(status.plugins[0]);
+ assert.equal(connectionReport(status).code,"invalid_response");
+ assert.equal(connectionReport({...statusFixture(),protocolVersion:"2"}).code,"invalid_response");
+});
+test("unexpected inspector messages do not perform requests", async () => {
+ let calls=0;
+ const bridge=createBridge(()=>{},async()=>{calls++;});
+ await bridge.handle(appear("next"));
+ await bridge.handle({...checkMessage(),action:prefix+"streamstart"});
+ await bridge.handle(checkMessage({kind:"execute",action:"stream.start"}));
+ assert.equal(calls,0);
+});
+test("late success cannot update a newly configured key", async () => {
+ const sent=[];let release;
+ const bridge=createBridge(m=>sent.push(m),async(url,options)=>new Promise(resolve=>{
+ release=()=>resolve({ok:true,json:async()=>({protocolVersion:"1",id:JSON.parse(options.body).id,success:true})});
+ }));
+ await bridge.handle(appear("next"));
+ const first=bridge.handle({event:"keyDown",context:"key"});
+ await bridge.handle({...appear("scene",{sceneName:"Other"}),event:"didReceiveSettings"});
+ release();await first;
+ assert.equal(sent.length,0);
+});
+test("late failure cannot update a reused key context", async () => {
+ const sent=[];let release;
+ const bridge=createBridge(m=>sent.push(m),()=>new Promise(resolve=>{release=resolve;}));
+ await bridge.handle(appear("next"));
+ const first=bridge.handle({event:"keyDown",context:"key"});
+ await bridge.handle({event:"willDisappear",context:"key"});
+ await bridge.handle(appear("recordstart"));
+ release({ok:false});await first;
+ assert.equal(sent.length,0);
+});
+test("overlapping connection checks issue one request", async () => {
+ let calls=0,release;const sent=[];
+ const bridge=createBridge(m=>sent.push(m),()=>{calls++;return new Promise(resolve=>{release=resolve;});});
+ await bridge.handle(appear("next"));
+ const first=bridge.handle(checkMessage());
+ await bridge.handle(checkMessage({requestId:"check-2"}));
+ release({ok:true,json:async()=>statusFixture()});await first;
+ assert.equal(calls,1);
+ assert.equal(sent[0].payload.requestId,"check-1");
+});
+
+
+test("connection diagnostics explain known causes in both languages without echoing server text", () => {
+ const { connectionReport } = require(path.join(pluginDir, "diagnostics.js"));
+ const report = connectionReport({protocolVersion:"1",version:"0.0.001",plugins:[
+ {id:"powerpoint",state:"unavailable",data:{reason:"no_slideshow"},message:{da:"secret",en:"secret"}},
+ {id:"obs",state:"unavailable",data:{reason:"authentication_failed"},message:{da:"secret",en:"secret"}}
+ ]});
+ assert.equal(report.code,"partial");
+ assert.match(report.checks[0].message.da,/intet slideshow/);
+ assert.match(report.checks[0].message.en,/no slideshow/);
+ assert.match(report.checks[1].message.da,/afviste adgangskoden/);
+ assert.match(report.checks[1].message.en,/rejected the password/);
+ assert.ok(!JSON.stringify(report).includes("secret"));
+});
+
+test("unknown diagnostic causes fall back safely and cannot override ready status", () => {
+ const { connectionReport } = require(path.join(pluginDir, "diagnostics.js"));
+ for (const reason of ["constructor","__proto__",{da:"secret"}]) {
+ const report=connectionReport({protocolVersion:"1",version:"0.0.001",plugins:[
+ {id:"powerpoint",state:"ready",data:{reason:"no_slideshow"}},
+ {id:"obs",state:"unavailable",data:{reason},message:{da:"secret",en:"secret"}}
+ ]});
+ assert.match(report.checks[0].message.en,/slideshow connected/);
+ assert.match(report.checks[1].message.en,/check the WebSocket/);
+ assert.ok(!JSON.stringify(report).includes("secret"));
+ }
+});