From 601912cc49856a3a728e8f0cbc46b50d488fba37 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:59:44 +0100 Subject: [PATCH 01/10] Add Control Hub 0.0.001 core, Stream Deck PowerPoint/OBS integrations and bilingual docs --- .github/workflows/ci.yml | 30 +++ .gitignore | 8 + AGENTS.md | 12 + CHANGELOG.md | 23 ++ CONTRIBUTING.md | 17 ++ ControlHub.slnx | 13 + Directory.Build.props | 13 + Plugins/AndroidLive/README.md | 17 ++ Plugins/AndroidRemote/README.md | 17 ++ Plugins/Audio/README.md | 17 ++ Plugins/FluxKeyboard/README.md | 17 ++ Plugins/Logitech/README.md | 17 ++ Plugins/Obs/ControlHub.Plugins.Obs.csproj | 1 + Plugins/Obs/ObsClient.cs | 84 +++++++ Plugins/Obs/ObsPlugin.cs | 54 ++++ Plugins/Obs/README.md | 11 + Plugins/PhysicalRemote/README.md | 17 ++ .../Planned/ControlHub.Plugins.Planned.csproj | 1 + Plugins/Planned/PlannedPlugin.cs | 15 ++ Plugins/Planned/README.md | 11 + Plugins/PowerPoint/ComSlideShowSession.cs | 97 ++++++++ .../ControlHub.Plugins.PowerPoint.csproj | 1 + Plugins/PowerPoint/PowerPointPlugin.cs | 71 ++++++ Plugins/PowerPoint/README.md | 11 + Plugins/StreamDeck/README.md | 11 + .../actions.js | 113 +++++++++ .../assets/action.svg | 1 + .../assets/action@2x.svg | 1 + .../assets/key.svg | 1 + .../assets/key@2x.svg | 1 + .../assets/plugin.svg | 1 + .../assets/plugin@2x.svg | 1 + .../bridge.js | 54 ++++ .../inspector.html | 11 + .../inspector.js | 42 ++++ .../manifest.json | 232 ++++++++++++++++++ .../plugin.js | 22 ++ README.en.md | 66 +++++ README.md | 67 ++++- VERSION | 1 + docs/project.da.md | 96 ++++++++ docs/project.en.md | 96 ++++++++ docs/protocol.da.md | 78 ++++++ docs/protocol.en.md | 78 ++++++ docs/references.md | 13 + docs/setup.da.md | 79 ++++++ docs/setup.en.md | 79 ++++++ docs/testing.da.md | 46 ++++ docs/testing.en.md | 46 ++++ docs/versioning.md | 21 ++ global.json | 7 + scripts/check-policy.cjs | 18 ++ .../ControlHub.Contracts.csproj | 1 + src/ControlHub.Contracts/Protocol.cs | 51 ++++ src/ControlHub.Core/CommandDispatcher.cs | 89 +++++++ src/ControlHub.Core/ControlHub.Core.csproj | 1 + src/ControlHub.Host/ControlHub.Host.csproj | 8 + src/ControlHub.Host/Program.cs | 73 ++++++ .../ControlHub.Tests/ControlHub.Tests.csproj | 13 + tests/ControlHub.Tests/DispatcherTests.cs | 125 ++++++++++ tests/ControlHub.Tests/ObsTransportTests.cs | 106 ++++++++ tests/ControlHub.Tests/PluginTests.cs | 129 ++++++++++ tests/host-smoke.cjs | 41 ++++ tests/streamdeck.test.cjs | 88 +++++++ 64 files changed, 2580 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 ControlHub.slnx create mode 100644 Directory.Build.props create mode 100644 Plugins/AndroidLive/README.md create mode 100644 Plugins/AndroidRemote/README.md create mode 100644 Plugins/Audio/README.md create mode 100644 Plugins/FluxKeyboard/README.md create mode 100644 Plugins/Logitech/README.md create mode 100644 Plugins/Obs/ControlHub.Plugins.Obs.csproj create mode 100644 Plugins/Obs/ObsClient.cs create mode 100644 Plugins/Obs/ObsPlugin.cs create mode 100644 Plugins/Obs/README.md create mode 100644 Plugins/PhysicalRemote/README.md create mode 100644 Plugins/Planned/ControlHub.Plugins.Planned.csproj create mode 100644 Plugins/Planned/PlannedPlugin.cs create mode 100644 Plugins/Planned/README.md create mode 100644 Plugins/PowerPoint/ComSlideShowSession.cs create mode 100644 Plugins/PowerPoint/ControlHub.Plugins.PowerPoint.csproj create mode 100644 Plugins/PowerPoint/PowerPointPlugin.cs create mode 100644 Plugins/PowerPoint/README.md create mode 100644 Plugins/StreamDeck/README.md create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/actions.js create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/action@2x.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/key@2x.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.svg create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/manifest.json create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/plugin.js create mode 100644 README.en.md create mode 100644 VERSION create mode 100644 docs/project.da.md create mode 100644 docs/project.en.md create mode 100644 docs/protocol.da.md create mode 100644 docs/protocol.en.md create mode 100644 docs/references.md create mode 100644 docs/setup.da.md create mode 100644 docs/setup.en.md create mode 100644 docs/testing.da.md create mode 100644 docs/testing.en.md create mode 100644 docs/versioning.md create mode 100644 global.json create mode 100644 scripts/check-policy.cjs create mode 100644 src/ControlHub.Contracts/ControlHub.Contracts.csproj create mode 100644 src/ControlHub.Contracts/Protocol.cs create mode 100644 src/ControlHub.Core/CommandDispatcher.cs create mode 100644 src/ControlHub.Core/ControlHub.Core.csproj create mode 100644 src/ControlHub.Host/ControlHub.Host.csproj create mode 100644 src/ControlHub.Host/Program.cs create mode 100644 tests/ControlHub.Tests/ControlHub.Tests.csproj create mode 100644 tests/ControlHub.Tests/DispatcherTests.cs create mode 100644 tests/ControlHub.Tests/ObsTransportTests.cs create mode 100644 tests/ControlHub.Tests/PluginTests.cs create mode 100644 tests/host-smoke.cjs create mode 100644 tests/streamdeck.test.cjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6a3eb6a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: Build and tests / Byg og test +on: + push: + branches: [main, 'feature/**'] + pull_request: + branches: [main] +permissions: + contents: read +jobs: + verify: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-node@v4 + with: + node-version: '24' + - run: dotnet restore ControlHub.slnx + - run: dotnet build ControlHub.slnx --no-restore --configuration Release + - run: dotnet test ControlHub.slnx --no-build --configuration Release --logger trx + - run: node --test tests/streamdeck.test.cjs + - run: node tests/host-smoke.cjs + - run: node scripts/check-policy.cjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..34bd8da --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +**/bin/ +**/obj/ +.vs/ +TestResults/ +artifacts/ +.env +*.user +*.streamDeckPlugin diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..dec341f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,12 @@ +# Projektregler / Project rules + +- Dansk: Kommunikér med ejeren på dansk. Dokumentation og brugervendte tekster skal være på dansk og engelsk. +- English: Communicate with the owner in Danish. Documentation and user-facing text must be Danish and English. +- Dansk: Prioritér Stream Deck sammen med PowerPoint og OBS Studio; derefter AndroidRemote. +- English: Prioritize Stream Deck with PowerPoint and OBS Studio, followed by AndroidRemote. +- Dansk: Alle pluginimplementationer og aktiver under Plugins/. Ingen ændring af præsentationsfiler eller fokusafhængige genveje. +- English: All plugin implementations and assets belong under Plugins/. Never modify presentation files or use focus-dependent shortcuts. +- Dansk: Brug arbejdsbranch og PR mod main. Byg og test. Rapportér faktisk implementering og resterende hardwaretest. +- English: Use a working branch and PR to main. Build and test. Report actual implementation and remaining hardware tests. +- Dansk: Ingen release eller tag uden ejerens godkendelse. Hver .100-grænse og skiftet til 0.1.000 kræver særskilt godkendelse. Følg docs/versioning.md. +- English: No release or tag without owner approval. Each .100 boundary and transition to 0.1.000 needs separate approval. Follow docs/versioning.md. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..69282d9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,23 @@ +# Ændringslog / Changelog + +## 0.0.001 — udviklingsversion / development version + +### Dansk +- C#/.NET 10-kontrakter, dispatcher og lokal autentificeret HTTP-host. +- Eksplicit pluginsystem med ærlig status for ikke-implementerede integrationer. +- PowerPoint COM-navigation på STA-tråd, uden filredigering eller tastaturgenveje. +- OBS WebSocket v5-klient med godkendelse og konkrete handlinger. +- Stream Deck-kildeplugin med 12 handlinger, dansk/engelsk opsætning og statusfeedback. +- Forberedte integrationsplaner for AndroidRemote, lyd, Logitech, Android Live, fysisk fjernkontrol og Flux Keyboard. +- Automatiske tests, CI på Windows/Linux og projektbeskrivelse på begge sprog. +- Fysisk test i det aktive miljø afventer. Ingen release eller tag. + +### English +- C#/.NET 10 contracts, dispatcher and authenticated local HTTP host. +- Explicit plugin system with truthful status for unimplemented integrations. +- PowerPoint COM navigation on an STA thread without file editing or keyboard shortcuts. +- OBS WebSocket v5 client with authentication and concrete actions. +- Stream Deck source plugin with 12 actions, Danish/English settings and status feedback. +- Prepared integration plans for AndroidRemote, audio, Logitech, Android Live, physical remote and Flux Keyboard. +- Automated tests, Windows/Linux CI and project description in both languages. +- Physical testing in the active environment remains pending. No release or tag. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..25d2ebc --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,17 @@ +# Bidrag / Contributing + +## Dansk + +Arbejd på en branch fra `main`, og åbn en PR mod `main`. Hold alle pluginimplementationer og deres aktiver under `Plugins/`. Bevar danske og engelske dokumenter samt UI-tekster i samme ændring; protokol- og kodeidentifikatorer forbliver engelske. + +Kør build, C#-tests, Stream Deck-tests, host-smoketest og kildekoderegler som beskrevet i installationsvejledningen. Beskriv præcist, om en integration er implementeret, simuleret, planlagt eller fysisk afprøvet. Brug ikke grønne enhedstests som bevis for hardwarefunktion. + +Ændr aldrig præsentationsfiler, og tilføj ingen fokusafhængige genveje. Gem aldrig tokens eller adgangskoder i kode, eksempler, testlogs eller profiler. Følg [versionsreglerne](docs/versioning.md). Release, tags og .100-grænser kræver ejerens eksplicitte godkendelse. + +## English + +Work on a branch from `main` and open a PR targeting `main`. Keep all plugin implementations and assets under `Plugins/`. Update Danish and English documentation and UI text together; protocol and code identifiers remain English. + +Run the build, C# tests, Stream Deck tests, host smoke test and source policy checks described in setup. State precisely whether an integration is implemented, simulated, planned or physically tested. Green unit tests do not prove hardware functionality. + +Never modify presentation files or add focus-dependent shortcuts. Never commit tokens or passwords in code, examples, test logs or profiles. Follow the [version policy](docs/versioning.md). Releases, tags and .100 boundaries require explicit owner approval. diff --git a/ControlHub.slnx b/ControlHub.slnx new file mode 100644 index 0000000..3e3f2c4 --- /dev/null +++ b/ControlHub.slnx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..4f588a5 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,13 @@ + + + net10.0 + enable + enable + true + 0.0.1 + 0.0.1.0 + 0.0.1.0 + 0.0.001 + true + + diff --git a/Plugins/AndroidLive/README.md b/Plugins/AndroidLive/README.md new file mode 100644 index 0000000..87918f6 --- /dev/null +++ b/Plugins/AndroidLive/README.md @@ -0,0 +1,17 @@ +# Android Live / Android Live + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `android-live`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Afklar om integrationen omfatter kamera, status eller styring. Fastlæg transport, parring og adgang. Denne integration er adskilt fra AndroidRemote. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `android-live`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Establish whether the integration covers a camera, status or control. Define transport, pairing and access. This integration is separate from AndroidRemote. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/AndroidRemote/README.md b/Plugins/AndroidRemote/README.md new file mode 100644 index 0000000..30ce577 --- /dev/null +++ b/Plugins/AndroidRemote/README.md @@ -0,0 +1,17 @@ +# AndroidRemote / AndroidRemote + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `androidremote`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Næste prioritet efter Stream Deck/PowerPoint/OBS. Afklar om navnet betyder en eksisterende app eller en ny klient. Design derefter en mobil knapflade, parring, TLS, enhedsgodkendelse, genkaldelse og status. Genbrug protokol v1; åbn ikke den eksisterende loopback-host på LAN. Ingen automatisk replay efter mobil genforbindelse. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `androidremote`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Next priority after Stream Deck/PowerPoint/OBS. Establish whether this means an existing app or a new client. Then design mobile buttons, pairing, TLS, device authorization, revocation and status. Reuse protocol v1; do not expose the existing loopback host on the LAN. Never automatically replay commands after mobile reconnection. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/Audio/README.md b/Plugins/Audio/README.md new file mode 100644 index 0000000..eae281c --- /dev/null +++ b/Plugins/Audio/README.md @@ -0,0 +1,17 @@ +# Lyd / Audio + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `audio`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Separat styring af operativsystemets lydenheder. Afklar platform, enhedsvalg og ønskede funktioner. Windows Core Audio er en mulig fremtidig adapter, ikke implementeret. OBS input.mute findes allerede i OBS-pluginet. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `audio`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Separate control of operating-system audio devices. Establish platform, device selection and required features. Windows Core Audio is a possible future adapter, not implemented. OBS input.mute is already part of the OBS plugin. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/FluxKeyboard/README.md b/Plugins/FluxKeyboard/README.md new file mode 100644 index 0000000..376ffcf --- /dev/null +++ b/Plugins/FluxKeyboard/README.md @@ -0,0 +1,17 @@ +# Flux Keyboard / Flux Keyboard + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `flux-keyboard`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Afklar præcis producent, model og tilgængelig dokumentation. Ingen antagelse om API eller SDK. Planlæg navngivne knaphændelser, status og capability-detektion efter verificering. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `flux-keyboard`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Establish the exact vendor, model and available documentation. Do not assume an API or SDK. Plan named key events, status and capability detection after verification. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/Logitech/README.md b/Plugins/Logitech/README.md new file mode 100644 index 0000000..1d10e10 --- /dev/null +++ b/Plugins/Logitech/README.md @@ -0,0 +1,17 @@ +# Logitech / Logitech + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `logitech`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Afklar konkret model og dokumenteret SDK/HID-protokol. Kortlæg enhedshændelser til navngivne kommandoer; anvend ikke globale tastaturgenveje. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `logitech`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Establish the exact model and documented SDK/HID protocol. Map device events to named commands; do not use global keyboard shortcuts. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/Obs/ControlHub.Plugins.Obs.csproj b/Plugins/Obs/ControlHub.Plugins.Obs.csproj new file mode 100644 index 0000000..8f74cf8 --- /dev/null +++ b/Plugins/Obs/ControlHub.Plugins.Obs.csproj @@ -0,0 +1 @@ + diff --git a/Plugins/Obs/ObsClient.cs b/Plugins/Obs/ObsClient.cs new file mode 100644 index 0000000..6c3eaec --- /dev/null +++ b/Plugins/Obs/ObsClient.cs @@ -0,0 +1,84 @@ +using System.Net.WebSockets; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using ControlHub.Contracts; + +namespace ControlHub.Plugins.Obs; + +public interface IObsClient +{ + Task RequestAsync(string requestType, object requestData, CancellationToken cancellationToken); +} + +public sealed class ObsRequestException : Exception; +public sealed class ObsClient : IObsClient +{ + private readonly Uri endpoint; + private readonly string? password; + public ObsClient(Uri endpoint, string? password) + { + if (!endpoint.IsLoopback || endpoint.Scheme != "ws" || !string.IsNullOrEmpty(endpoint.UserInfo) || + endpoint.AbsolutePath != "/" || !string.IsNullOrEmpty(endpoint.Query) || !string.IsNullOrEmpty(endpoint.Fragment)) + throw new ArgumentException("OBS must use a local ws:// endpoint / OBS skal bruge en lokal ws://-adresse.", nameof(endpoint)); + this.endpoint = endpoint; + this.password = password; + } + + public static string Authenticate(string password, string salt, string challenge) + { + var secret = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(password + salt))); + return Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(secret + challenge))); + } + + public async Task RequestAsync(string requestType, object requestData, CancellationToken cancellationToken) + { + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(endpoint, cancellationToken); + var hello = await ReceiveAsync(socket, cancellationToken); + if (hello.GetProperty("op").GetInt32() != 0) throw new ObsRequestException(); + var identify = new Dictionary { ["rpcVersion"] = 1, ["eventSubscriptions"] = 0 }; + if (hello.GetProperty("d").TryGetProperty("authentication", out var auth)) + { + if (string.IsNullOrEmpty(password)) throw new ObsRequestException(); + identify["authentication"] = Authenticate(password, auth.GetProperty("salt").GetString()!, auth.GetProperty("challenge").GetString()!); + } + await SendAsync(socket, new { op = 1, d = identify }, cancellationToken); + var identified = await ReceiveAsync(socket, cancellationToken); + if (identified.GetProperty("op").GetInt32() != 2 || + identified.GetProperty("d").GetProperty("negotiatedRpcVersion").GetInt32() != 1) throw new ObsRequestException(); + var requestId = Guid.NewGuid().ToString("D"); + await SendAsync(socket, new { op = 6, d = new { requestType, requestId, requestData } }, cancellationToken); + while (true) + { + var response = await ReceiveAsync(socket, cancellationToken); + if (response.GetProperty("op").GetInt32() == 5) continue; + if (response.GetProperty("op").GetInt32() != 7) throw new ObsRequestException(); + var data = response.GetProperty("d"); + if (data.GetProperty("requestId").GetString() != requestId || + data.GetProperty("requestType").GetString() != requestType) throw new ObsRequestException(); + if (!data.GetProperty("requestStatus").GetProperty("result").GetBoolean()) throw new ObsRequestException(); + return data.TryGetProperty("responseData", out var body) ? body.Clone() : null; + } + } + + private static Task SendAsync(WebSocket socket, object message, CancellationToken cancellationToken) + => socket.SendAsync(new ArraySegment(JsonSerializer.SerializeToUtf8Bytes(message, Wire.Json)), + WebSocketMessageType.Text, true, cancellationToken); + + private static async Task ReceiveAsync(WebSocket socket, CancellationToken cancellationToken) + { + using var stream = new MemoryStream(); + var buffer = new byte[8192]; + WebSocketReceiveResult result; + do + { + result = await socket.ReceiveAsync(new ArraySegment(buffer), cancellationToken); + if (result.MessageType != WebSocketMessageType.Text || stream.Length + result.Count > 1_048_576) + throw new ObsRequestException(); + stream.Write(buffer, 0, result.Count); + } while (!result.EndOfMessage); + using var document = JsonDocument.Parse(stream.ToArray(), new JsonDocumentOptions { MaxDepth = 32 }); + return document.RootElement.Clone(); + } +} diff --git a/Plugins/Obs/ObsPlugin.cs b/Plugins/Obs/ObsPlugin.cs new file mode 100644 index 0000000..01f7200 --- /dev/null +++ b/Plugins/Obs/ObsPlugin.cs @@ -0,0 +1,54 @@ +using ControlHub.Contracts; + +namespace ControlHub.Plugins.Obs; + +public sealed class ObsPlugin(IObsClient client) : IHubPlugin +{ + public PluginDescriptor Descriptor { get; } = new("obs", new("OBS Studio", "OBS Studio"), "experimental", + ["scene.switch", "record.start", "record.stop", "stream.start", "stream.stop", "input.mute"]); + public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) + { + string request; + object data = new { }; + switch (command.Action) + { + case "scene.switch": + if (!Wire.OnlyArguments(command.Arguments, "sceneName") || !Wire.StringArgument(command.Arguments, "sceneName", out var scene)) + return Invalid(command); + request = "SetCurrentProgramScene"; data = new { sceneName = scene }; break; + case "input.mute": + if (!Wire.OnlyArguments(command.Arguments, "inputName", "muted") || + !Wire.StringArgument(command.Arguments, "inputName", out var input) || + !command.Arguments.TryGetProperty("muted", out var mute) || + mute.ValueKind is not (System.Text.Json.JsonValueKind.True or System.Text.Json.JsonValueKind.False)) + return Invalid(command); + request = "SetInputMute"; data = new { inputName = input, inputMuted = mute.GetBoolean() }; break; + case "record.start": request = "StartRecord"; break; + case "record.stop": request = "StopRecord"; break; + case "stream.start": request = "StartStream"; break; + case "stream.stop": request = "StopStream"; break; + default: return Wire.Result(command, false, "unsupported_action", "Ukendt OBS-handling.", "Unknown OBS action."); + } + if (command.Action is not ("scene.switch" or "input.mute") && !Wire.OnlyArguments(command.Arguments)) return Invalid(command); + try + { + await client.RequestAsync(request, data, cancellationToken); + return Wire.Result(command, true, "ok", "OBS bekræftede handlingen.", "OBS acknowledged the action."); + } + catch (ObsRequestException) + { + return Wire.Result(command, false, "obs_rejected", "OBS-forbindelse eller handling afvist. Kontrollér status.", + "OBS connection or request rejected. Check status."); + } + } + private static CommandResult Invalid(Command command) => Wire.Result(command, false, "invalid_arguments", "Ugyldige OBS-argumenter.", "Invalid OBS arguments."); + + public async ValueTask GetStatusAsync(CancellationToken cancellationToken) + { + var scene = await client.RequestAsync("GetCurrentProgramScene", new { }, cancellationToken); + var recording = await client.RequestAsync("GetRecordStatus", new { }, cancellationToken); + var streaming = await client.RequestAsync("GetStreamStatus", new { }, cancellationToken); + return new("obs", "ready", new("OBS tilsluttet.", "OBS connected."), Wire.Data(new { scene, recording, streaming })); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/Plugins/Obs/README.md b/Plugins/Obs/README.md new file mode 100644 index 0000000..6ebfcaa --- /dev/null +++ b/Plugins/Obs/README.md @@ -0,0 +1,11 @@ +# Obs + +## Dansk +Implementeret WebSocket v5-adapter; fysisk OBS-test afventer. Kun lokal server. + +Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md). + +## English +Implemented WebSocket v5 adapter; physical OBS testing pending. Local server only. + +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/PhysicalRemote/README.md b/Plugins/PhysicalRemote/README.md new file mode 100644 index 0000000..934e604 --- /dev/null +++ b/Plugins/PhysicalRemote/README.md @@ -0,0 +1,17 @@ +# Fysisk fjernkontrol / Physical remote + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `physical-remote`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Afklar USB, HID, seriel, Bluetooth eller netværk og den konkrete model. Kræv eksplicit enhedsvalg, debounce, tryk/slip-semantik og kontrolleret reconnect. Ingen fokusbaserede tastetryk. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `physical-remote`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Establish USB, HID, serial, Bluetooth or network transport and the exact device model. Require explicit device selection, debounce, press/release semantics and controlled reconnect. No focus-based key injection. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/Planned/ControlHub.Plugins.Planned.csproj b/Plugins/Planned/ControlHub.Plugins.Planned.csproj new file mode 100644 index 0000000..8f74cf8 --- /dev/null +++ b/Plugins/Planned/ControlHub.Plugins.Planned.csproj @@ -0,0 +1 @@ + diff --git a/Plugins/Planned/PlannedPlugin.cs b/Plugins/Planned/PlannedPlugin.cs new file mode 100644 index 0000000..e253dc4 --- /dev/null +++ b/Plugins/Planned/PlannedPlugin.cs @@ -0,0 +1,15 @@ +using ControlHub.Contracts; + +namespace ControlHub.Plugins.Planned; + +// Explicit capability placeholders. They never report successful device execution. +// Eksplicitte pladsholdere. De rapporterer aldrig vellykket enhedsstyring. +public sealed class PlannedPlugin(string id, LocalizedText name) : IHubPlugin +{ + public PluginDescriptor Descriptor { get; } = new(id, name, "planned", []); + public ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) + => ValueTask.FromResult(Wire.Result(command, false, "not_implemented", "Integrationen er planlagt.", "Integration is planned.")); + public ValueTask GetStatusAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(new PluginStatus(Descriptor.Id, "not_implemented", new("Integrationen er planlagt.", "Integration is planned."))); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/Plugins/Planned/README.md b/Plugins/Planned/README.md new file mode 100644 index 0000000..a21234c --- /dev/null +++ b/Plugins/Planned/README.md @@ -0,0 +1,11 @@ +# Planned + +## Dansk +Fælles statuspladsholder for endnu ikke implementerede plugins. Udfører ingen enhedshandlinger. + +Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md). + +## English +Shared status placeholder for unimplemented plugins. Executes no device actions. + +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/PowerPoint/ComSlideShowSession.cs b/Plugins/PowerPoint/ComSlideShowSession.cs new file mode 100644 index 0000000..b1821b3 --- /dev/null +++ b/Plugins/PowerPoint/ComSlideShowSession.cs @@ -0,0 +1,97 @@ +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace ControlHub.Plugins.PowerPoint; + +[SupportedOSPlatform("windows")] +public sealed class ComSlideShowSession : ISlideShowSession +{ + private readonly BlockingCollection queue = new(); + private readonly Thread thread; + private int disposed; + public ComSlideShowSession() + { + thread = new Thread(() => { foreach (var action in queue.GetConsumingEnumerable()) action(); }) + { IsBackground = true, Name = "ControlHub.PowerPoint.STA" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + private async Task InvokeAsync(Func action, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.Add(() => + { + if (cancellationToken.IsCancellationRequested) { completion.TrySetCanceled(cancellationToken); return; } + try { completion.TrySetResult(action()); } + catch (Exception ex) { completion.TrySetException(ex); } + }, cancellationToken); + // COM cannot be forcibly cancelled; the client must reconcile an unknown result. + // COM kan ikke tvangsafbrydes; klienten skal kontrollere status efter timeout. + return await completion.Task.WaitAsync(cancellationToken); + } + + public Task ReadAsync(CancellationToken cancellationToken) + => InvokeAsync(() => WithView((view, count) => new SlideShowSnapshot((int)view.CurrentShowPosition, count, (int)view.State)), cancellationToken); + + public async Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken) + { + await InvokeAsync(() => WithView((view, count) => + { + cancellationToken.ThrowIfCancellationRequested(); + switch (action) + { + case "next": view.Next(); break; + case "previous": view.Previous(); break; + case "goto": + if (slide is null || slide < 1 || slide > count) throw new ArgumentOutOfRangeException(nameof(slide)); + view.GotoSlide(slide.Value, -1); break; + case "black": view.State = 3; break; + case "resume": view.State = 1; break; + default: throw new ArgumentException("Unknown action / Ukendt handling.", nameof(action)); + } + return true; + }), cancellationToken); + } + + private static T WithView(Func action) + { + var objects = new List(); + object Track(object value) { objects.Add(value); return value; } + try + { + var clsid = new Guid("91493441-5A91-11CF-8700-00AA0060263B"); + GetActiveObject(ref clsid, IntPtr.Zero, out var active); + dynamic app = Track(active); + dynamic windows = Track(app.SlideShowWindows); + if ((int)windows.Count != 1) throw new SlideShowUnavailableException(); + dynamic window = Track(windows.Item(1)); + dynamic presentation = Track(window.Presentation); + dynamic slides = Track(presentation.Slides); + dynamic view = Track(window.View); + return action(view, (int)slides.Count); + } + catch (COMException) { throw new SlideShowUnavailableException(); } + finally + { + for (var i = objects.Count - 1; i >= 0; i--) + if (Marshal.IsComObject(objects[i])) Marshal.ReleaseComObject(objects[i]); + } + } + + [DllImport("oleaut32.dll", PreserveSig = false)] + private static extern void GetActiveObject(ref Guid clsid, IntPtr reserved, + [MarshalAs(UnmanagedType.IUnknown)] out object result); + + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref disposed, 1) == 0) + { + queue.CompleteAdding(); + thread.Join(TimeSpan.FromSeconds(2)); + } + return ValueTask.CompletedTask; + } +} diff --git a/Plugins/PowerPoint/ControlHub.Plugins.PowerPoint.csproj b/Plugins/PowerPoint/ControlHub.Plugins.PowerPoint.csproj new file mode 100644 index 0000000..8f74cf8 --- /dev/null +++ b/Plugins/PowerPoint/ControlHub.Plugins.PowerPoint.csproj @@ -0,0 +1 @@ + diff --git a/Plugins/PowerPoint/PowerPointPlugin.cs b/Plugins/PowerPoint/PowerPointPlugin.cs new file mode 100644 index 0000000..c27aef3 --- /dev/null +++ b/Plugins/PowerPoint/PowerPointPlugin.cs @@ -0,0 +1,71 @@ +using ControlHub.Contracts; + +namespace ControlHub.Plugins.PowerPoint; + +public sealed record SlideShowSnapshot(int Position, int SlideCount, int State); +public interface ISlideShowSession : IAsyncDisposable +{ + Task ReadAsync(CancellationToken cancellationToken); + Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken); +} + +public sealed class PowerPointPlugin : IHubPlugin +{ + private readonly ISlideShowSession? session; + public PluginDescriptor Descriptor { get; } = new("powerpoint", new("PowerPoint", "PowerPoint"), "experimental", + ["next", "previous", "goto", "black", "resume"]); + public PowerPointPlugin(ISlideShowSession? session = null) + { + this.session = session ?? (OperatingSystem.IsWindows() ? new ComSlideShowSession() : null); + } + + public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) + { + if (!Descriptor.Actions.Contains(command.Action)) + return Wire.Result(command, false, "unsupported_action", "Ukendt handling.", "Unknown action."); + int? slide = null; + if (command.Action == "goto") + { + if (!Wire.OnlyArguments(command.Arguments, "slide") || + !command.Arguments.TryGetProperty("slide", out var element) || + element.ValueKind != System.Text.Json.JsonValueKind.Number || !element.TryGetInt32(out var number) || number < 1) + return Wire.Result(command, false, "invalid_arguments", "Slide skal være et positivt heltal.", "Slide must be a positive integer."); + slide = number; + } + else if (!Wire.OnlyArguments(command.Arguments)) + return Wire.Result(command, false, "invalid_arguments", "Handlingen tager ingen argumenter.", "This action takes no arguments."); + if (session is null) + return Wire.Result(command, false, "unsupported_platform", "PowerPoint COM kræver Windows.", "PowerPoint COM requires Windows."); + try + { + await session.ApplyAsync(command.Action, slide, cancellationToken); + return Wire.Result(command, true, "ok", "Slideshow-kommando udført.", "Slideshow command completed."); + } + catch (SlideShowUnavailableException) + { + return Wire.Result(command, false, "slideshow_unavailable", + "Start præcis ét PowerPoint-slideshow manuelt.", "Start exactly one PowerPoint slideshow manually."); + } + catch (ArgumentOutOfRangeException) + { + return Wire.Result(command, false, "invalid_arguments", "Slide ligger uden for præsentationen.", "Slide is outside the presentation."); + } + } + + public async ValueTask 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) + { + return new("powerpoint", "unavailable", new("Intet entydigt slideshow.", "No unambiguous slideshow.")); + } + } + + public ValueTask DisposeAsync() => session?.DisposeAsync() ?? ValueTask.CompletedTask; +} +public sealed class SlideShowUnavailableException : Exception; 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..bbff82c --- /dev/null +++ b/Plugins/StreamDeck/README.md @@ -0,0 +1,11 @@ +# StreamDeck + +## Dansk +Implementeret kildeplugin med 12 handlinger; installation og hardwaretest afventer. + +Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md). + +## English +Implemented source plugin with 12 actions; installation and hardware testing pending. + +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.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.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..e64759e --- /dev/null +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js @@ -0,0 +1,54 @@ +"use strict"; +const { definition, makeCommand, statusTitle } = require("./actions.js"); +function createBridge(send, fetchImpl = fetch) { + const contexts = new Map(); + const busy = new Set(); + function title(context, text) { send({ event: "setTitle", context, payload: { title: text, target: 0 } }); } + async function invoke(context) { + const item = contexts.get(context); + if (!item || busy.has(context)) return; + busy.add(context); + try { + const settings = item.settings; + if (typeof settings.token !== "string" || settings.token.length < 32) throw new Error("Token missing"); + 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"); + const result = await response.json(); + if (!contexts.has(context)) 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"); + title(context, definition(item.action)[settings.language === "en" ? "en" : "da"]); + send({ event: "showOk", context }); + } + } catch { + if (contexts.has(context)) { + 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 === "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/inspector.html b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html new file mode 100644 index 0000000..a73f858 --- /dev/null +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html @@ -0,0 +1,11 @@ + +Control Hub + + + +
+
+
+
+

+ 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..e62bd0a --- /dev/null +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js @@ -0,0 +1,42 @@ +"use strict"; +let socket, context, currentSettings = {}, action; +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 eller eksportér ikke profiler med token. En fejl kan betyde ukendt udfald; kontrollér status før nyt tryk.", save: "Gem", saved: "Gemt" }, + 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 or export profiles containing it. An error can mean an unknown outcome; check status before pressing again.", save: "Save", saved: "Saved" } +}; +function render() { + const language = el("language").value; + document.documentElement.lang = language; + for (const [id, value] of Object.entries(translations[language])) if (id !== "saved") el(id).textContent = value; +} +function load(settings) { + currentSettings = settings; + 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); + context = uuid; action = data.action; + 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 })); + socket.onmessage = event => { + const message = JSON.parse(event.data); + if (message.event === "didReceiveSettings") load(message.payload.settings); + }; +} +el("language").onchange = render; +el("save").onclick = () => { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + const settings = { ...currentSettings, token: el("token").value, language: el("language").value, + slide: el("slide").value, sceneName: el("sceneName").value, inputName: el("inputName").value, muted: el("muted").value === "true" }; + socket.send(JSON.stringify({ event: "setSettings", context, payload: settings })); + el("saved").textContent = translations[settings.language].saved; +}; +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..4b62a7b --- /dev/null +++ b/README.en.md @@ -0,0 +1,66 @@ +# 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) +- [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 desktop GUI, service installer or persistent queue | +| 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 and status key | Source plugin for manual development installation; hardware acceptance pending | +| AndroidRemote | Plugin ID, status placeholder and integration plan | No Android app or pairing yet | +| 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 + +Requirements: .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 +``` + +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..0cd0e02 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,66 @@ -# Control Hub +# Control Hub · 0.0.001 -Source repository for Control Hub. Development is proposed through pull requests to main. +**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) +- [Kommando- og statusprotokol](docs/protocol.da.md) · [English](docs/protocol.en.md) +- [Testplan og acceptkriterier](docs/testing.da.md) · [English](docs/testing.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 desktop-GUI, serviceinstallation eller vedvarende kø | +| 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 og statusknap | Kildeplugin til manuel udviklingsinstallation; endnu ikke hardwaregodkendt | +| AndroidRemote | Plugin-id, statuspladsholder og integrationsplan | Ingen Android-app eller parring endnu | +| 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 + +Krav: .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 +``` + +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/project.da.md b/docs/project.da.md new file mode 100644 index 0000000..806f8bd --- /dev/null +++ b/docs/project.da.md @@ -0,0 +1,96 @@ +# 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. + +En visuel desktopkontrolcentral, brugerprofiler, makroer, samlet scene-/slideautomatik og installation som Windows-service ligger 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 · planlagt"] -.->|"Fremtidig parret transport"| 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. + +## 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ø. diff --git a/docs/project.en.md b/docs/project.en.md new file mode 100644 index 0000000..8027164 --- /dev/null +++ b/docs/project.en.md @@ -0,0 +1,96 @@ +# 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 desktop control dashboard, user profiles, macros, combined scene/slide automation and Windows service installation are 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 · planned"] -.->|"Future paired transport"| 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. + +## 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. diff --git a/docs/protocol.da.md b/docs/protocol.da.md new file mode 100644 index 0000000..635bdd6 --- /dev/null +++ b/docs/protocol.da.md @@ -0,0 +1,78 @@ +# 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. diff --git a/docs/protocol.en.md b/docs/protocol.en.md new file mode 100644 index 0000000..ec8cb30 --- /dev/null +++ b/docs/protocol.en.md @@ -0,0 +1,78 @@ +# 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. diff --git a/docs/references.md b/docs/references.md new file mode 100644 index 0000000..cf97c3c --- /dev/null +++ b/docs/references.md @@ -0,0 +1,13 @@ +# 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/) + +Henvisninger beskriver API'er; de er ikke bevis for lokal hardwaretest. / References describe APIs; they are not evidence of local hardware testing. diff --git a/docs/setup.da.md b/docs/setup.da.md new file mode 100644 index 0000000..9f36a5c --- /dev/null +++ b/docs/setup.da.md @@ -0,0 +1,79 @@ +# Installation og betjening + +[English](setup.en.md) · [Forside](../README.md) + +## Forudsætninger + +- 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 +node scripts/check-policy.cjs +``` + +`node tests/host-smoke.cjs` starter en kortvarig testhost på port 5187. Stop din normale host først. 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. 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. + +Dette er en manuel udviklingsinstallation fra kildekode. Der er ikke udgivet en Marketplace-pakke, installer, release eller 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. diff --git a/docs/setup.en.md b/docs/setup.en.md new file mode 100644 index 0000000..cfaf8c5 --- /dev/null +++ b/docs/setup.en.md @@ -0,0 +1,79 @@ +# Setup and operation + +[Dansk](setup.da.md) · [Home](../README.en.md) + +## Prerequisites + +- 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 +node scripts/check-policy.cjs +``` + +`node tests/host-smoke.cjs` starts a temporary test host on port 5187. Stop your normal host first. 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. Enter exact OBS scene and input names. Go-to requires a positive slide number. Mute specifies a desired state rather than blindly toggling. + +This is a manual development installation from source. No Marketplace package, installer, release or tag has been published. + +## 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. diff --git a/docs/testing.da.md b/docs/testing.da.md new file mode 100644 index 0000000..6c4afc9 --- /dev/null +++ b/docs/testing.da.md @@ -0,0 +1,46 @@ +# Testplan og accept + +[English](testing.en.md) + +## Automatiske kontroller + +- 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. +- 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ø. diff --git a/docs/testing.en.md b/docs/testing.en.md new file mode 100644 index 0000000..2afe5c7 --- /dev/null +++ b/docs/testing.en.md @@ -0,0 +1,46 @@ +# Test plan and acceptance + +[Dansk](testing.da.md) + +## Automated checks + +- 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. +- 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. 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/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/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..0979cdf --- /dev/null +++ b/src/ControlHub.Core/CommandDispatcher.cs @@ -0,0 +1,89 @@ +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) + { + 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 + { + 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.Host/ControlHub.Host.csproj b/src/ControlHub.Host/ControlHub.Host.csproj new file mode 100644 index 0000000..a2f8be6 --- /dev/null +++ b/src/ControlHub.Host/ControlHub.Host.csproj @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/ControlHub.Host/Program.cs b/src/ControlHub.Host/Program.cs new file mode 100644 index 0000000..4b7af6d --- /dev/null +++ b/src/ControlHub.Host/Program.cs @@ -0,0 +1,73 @@ +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.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 builder = WebApplication.CreateBuilder(args); +builder.WebHost.ConfigureKestrel(options => +{ + options.Listen(IPAddress.Loopback, 5187); + 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 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 PlannedPlugin("androidremote", new("AndroidRemote", "AndroidRemote")), + 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(); +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(); +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"); +try { await app.RunAsync(); } +finally { foreach (var plugin in plugins) await plugin.DisposeAsync(); } diff --git a/tests/ControlHub.Tests/ControlHub.Tests.csproj b/tests/ControlHub.Tests/ControlHub.Tests.csproj new file mode 100644 index 0000000..f842a6b --- /dev/null +++ b/tests/ControlHub.Tests/ControlHub.Tests.csproj @@ -0,0 +1,13 @@ + + falsetrue + + + + 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..5f243ca --- /dev/null +++ b/tests/ControlHub.Tests/ObsTransportTests.cs @@ -0,0 +1,106 @@ +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)); + await Assert.ThrowsAsync(() => + new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token)); + } + + [Fact] + public async Task MissingPasswordFailsBeforeSendingCommand() + { + await using var server = await FakeServer.StartAsync(true); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + await Assert.ThrowsAsync(() => + new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token)); + 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) + { + 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 + { + 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 (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); + 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..cd8f4e3 --- /dev/null +++ b/tests/ControlHub.Tests/PluginTests.cs @@ -0,0 +1,129 @@ +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("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("androidremote", new("AndroidRemote", "AndroidRemote")); + Assert.Empty(plugin.Descriptor.Actions); + Assert.Equal("not_implemented", (await plugin.GetStatusAsync(default)).State); + Assert.False((await plugin.ExecuteAsync(DispatcherTests.Command("androidremote"), 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 Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken) + { + if (Unavailable) throw new SlideShowUnavailableException(); + Action = action; Slide = slide; return Task.CompletedTask; + } + public Task ReadAsync(CancellationToken cancellationToken) + => Unavailable ? throw new SlideShowUnavailableException() : 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/host-smoke.cjs b/tests/host-smoke.cjs new file mode 100644 index 0000000..e8b3f81 --- /dev/null +++ b/tests/host-smoke.cjs @@ -0,0 +1,41 @@ +const assert = require("node:assert/strict"); +const { spawn } = require("node:child_process"); +const { randomBytes, randomUUID } = require("node:crypto"); +const token = randomBytes(32).toString("hex"); +const child = spawn("dotnet", ["src/ControlHub.Host/bin/Release/net10.0/ControlHub.Host.dll"], + { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); +let log = ""; +child.stdout.on("data", d => { log = (log + d).slice(-4000); }); +child.stderr.on("data", d => { log = (log + d).slice(-4000); }); +const base = "http://127.0.0.1:5187/api/v1/"; +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((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")); + 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,"not_implemented"); + assert.equal(status.plugins.find(p=>p.id==="obs").state,"unavailable"); + console.log("Host smoke checks passed / Host-kontrol bestået"); + } finally { child.kill(); } +})().catch(error=>{ console.error(error); process.exitCode=1; }); diff --git a/tests/streamdeck.test.cjs b/tests/streamdeck.test.cjs new file mode 100644 index 0000000..491db98 --- /dev/null +++ b/tests/streamdeck.test.cjs @@ -0,0 +1,88 @@ +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); +}); From ca58061674ec83d65deb508c6e5bab96b06cade3 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:54:47 +0100 Subject: [PATCH 02/10] Add read-only Stream Deck connection checks and validate plugin assets --- .github/workflows/ci.yml | 61 ++--- CHANGELOG.md | 48 ++-- .../assets/plugin.png | Bin 0 -> 400 bytes .../assets/plugin@2x.png | Bin 0 -> 709 bytes .../bridge.js | 38 ++- .../diagnostics.js | 37 +++ .../inspector.html | 22 +- .../inspector.js | 67 ++++- README.en.md | 132 ++++----- README.md | 132 ++++----- docs/project.da.md | 190 ++++++------- docs/project.en.md | 190 ++++++------- docs/setup.da.md | 159 +++++------ docs/setup.en.md | 159 +++++------ docs/testing.da.md | 95 +++---- docs/testing.en.md | 95 +++---- tests/host-smoke.cjs | 95 ++++--- tests/inspector.test.cjs | 58 ++++ tests/streamdeck.test.cjs | 254 +++++++++++++----- 19 files changed, 1070 insertions(+), 762 deletions(-) create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin.png create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/assets/plugin@2x.png create mode 100644 Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js create mode 100644 tests/inspector.test.cjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a3eb6a..ef4c93c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,30 +1,31 @@ -name: Build and tests / Byg og test -on: - push: - branches: [main, 'feature/**'] - pull_request: - branches: [main] -permissions: - contents: read -jobs: - verify: - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '10.0.x' - - uses: actions/setup-node@v4 - with: - node-version: '24' - - run: dotnet restore ControlHub.slnx - - run: dotnet build ControlHub.slnx --no-restore --configuration Release - - run: dotnet test ControlHub.slnx --no-build --configuration Release --logger trx - - run: node --test tests/streamdeck.test.cjs - - run: node tests/host-smoke.cjs - - run: node scripts/check-policy.cjs +name: Build and tests / Byg og test +on: + push: + branches: [main, 'feature/**'] + pull_request: + branches: [main] +permissions: + contents: read +jobs: + verify: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-node@v4 + with: + node-version: '24' + - run: dotnet restore ControlHub.slnx + - run: dotnet build ControlHub.slnx --no-restore --configuration Release + - run: dotnet test ControlHub.slnx --no-build --configuration Release --logger trx + - run: node --test tests/streamdeck.test.cjs tests/inspector.test.cjs + - run: npx --yes --package=@elgato/cli@1.10.3 streamdeck validate --no-update-check Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin + - run: node tests/host-smoke.cjs + - run: node scripts/check-policy.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 69282d9..e4eae60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,23 +1,29 @@ -# Ændringslog / Changelog - -## 0.0.001 — udviklingsversion / development version - +# Ændringslog / Changelog + +## 0.0.001 — udviklingsversion / development version + ### Dansk -- C#/.NET 10-kontrakter, dispatcher og lokal autentificeret HTTP-host. -- Eksplicit pluginsystem med ærlig status for ikke-implementerede integrationer. -- PowerPoint COM-navigation på STA-tråd, uden filredigering eller tastaturgenveje. -- OBS WebSocket v5-klient med godkendelse og konkrete handlinger. -- Stream Deck-kildeplugin med 12 handlinger, dansk/engelsk opsætning og statusfeedback. -- Forberedte integrationsplaner for AndroidRemote, lyd, Logitech, Android Live, fysisk fjernkontrol og Flux Keyboard. -- Automatiske tests, CI på Windows/Linux og projektbeskrivelse på begge sprog. -- Fysisk test i det aktive miljø afventer. Ingen release eller tag. - +- Forbindelsestest i Stream Deck-indstillingerne med separat status for Control Hub, PowerPoint og OBS. +- Beskyttelse mod forsinket knapfeedback efter profil-/indstillingsskift. +- Hovedikon i krævet PNG-format og officiel Elgato-validering i CI. +- C#/.NET 10-kontrakter, dispatcher og lokal autentificeret HTTP-host. +- Eksplicit pluginsystem med ærlig status for ikke-implementerede integrationer. +- PowerPoint COM-navigation på STA-tråd, uden filredigering eller tastaturgenveje. +- OBS WebSocket v5-klient med godkendelse og konkrete handlinger. +- Stream Deck-kildeplugin med 12 handlinger, dansk/engelsk opsætning og statusfeedback. +- Forberedte integrationsplaner for AndroidRemote, lyd, Logitech, Android Live, fysisk fjernkontrol og Flux Keyboard. +- Automatiske tests, CI på Windows/Linux og projektbeskrivelse på begge sprog. +- Fysisk test i det aktive miljø afventer. Ingen release eller tag. + ### English -- C#/.NET 10 contracts, dispatcher and authenticated local HTTP host. -- Explicit plugin system with truthful status for unimplemented integrations. -- PowerPoint COM navigation on an STA thread without file editing or keyboard shortcuts. -- OBS WebSocket v5 client with authentication and concrete actions. -- Stream Deck source plugin with 12 actions, Danish/English settings and status feedback. -- Prepared integration plans for AndroidRemote, audio, Logitech, Android Live, physical remote and Flux Keyboard. -- Automated tests, Windows/Linux CI and project description in both languages. -- Physical testing in the active environment remains pending. No release or tag. +- Connection check in Stream Deck settings with separate Control Hub, PowerPoint and OBS status. +- Protection against late key feedback after profile/settings changes. +- Main icon in the required PNG format and official Elgato validation in CI. +- C#/.NET 10 contracts, dispatcher and authenticated local HTTP host. +- Explicit plugin system with truthful status for unimplemented integrations. +- PowerPoint COM navigation on an STA thread without file editing or keyboard shortcuts. +- OBS WebSocket v5 client with authentication and concrete actions. +- Stream Deck source plugin with 12 actions, Danish/English settings and status feedback. +- Prepared integration plans for AndroidRemote, audio, Logitech, Android Live, physical remote and Flux Keyboard. +- Automated tests, Windows/Linux CI and project description in both languages. +- Physical testing in the active environment remains pending. No release or tag. 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 0000000000000000000000000000000000000000..70ab2ade32dd1748bfd28a9a908ac9c52fedb8f8 GIT binary patch literal 400 zcmV;B0dM|^P)1NV7i`tDD~4BY;T8Myza47>dmGjMw% zX5cLd^%vA)|M27C%+Z2kXBTl!MfQU-jI+Tlt6voCD0@CD6z5&u{@<>)`oFl52YoCofd%v4 z75}v(lIUk)2?*bZ2D3vDoh*C+4d$zmV3siU9Bvlgr(=*N(ks#A(JNaN(=+2I(yM68 zrf1rBG2G|U%R*6ow>gkzqJjGtx-=7wJ(QshVK*OIS_(2-MBm*T urS%PJq(Xw%?J*Ub`j0`u2=^HS0|Nl+A1NQq&15zJ00000q_CLsD+o=mQ0ZpjX zrOr5O`lyzp{IH#%`nr^&`ocR#`N|?e_0nmC>b2o0*^A#L!dLem z^^Y$i24ds^Ir&f6Qh#-ABr-`T(~pq|n+YXbL4BLqxD&;F$Q7)t24!tl00000NkvXXu0mjfBJxRH literal 0 HcmV?d00001 diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js index e64759e..77d1817 100644 --- a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/bridge.js @@ -1,16 +1,43 @@ "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 (typeof settings.token !== "string" || settings.token.length < 32) throw new Error("Token missing"); + 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"), { @@ -20,18 +47,18 @@ function createBridge(send, fetchImpl = fetch) { signal: AbortSignal.timeout(isStatus ? 35000 : 12000), redirect: "error" }); - if (!response.ok) throw new Error("HTTP error"); + if (!response.ok) throw new Error("HTTP error / HTTP-fejl"); const result = await response.json(); - if (!contexts.has(context)) return; + 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"); + 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 (contexts.has(context)) { + if (current(context, item)) { title(context, item.settings.language === "en" ? "Check\nstatus" : "Tjek\nstatus"); send({ event: "showAlert", context }); } @@ -44,6 +71,7 @@ function createBridge(send, fetchImpl = fetch) { 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() { 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..456c7b6 --- /dev/null +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js @@ -0,0 +1,37 @@ +"use strict"; +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"; + const 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." }; + 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 index a73f858..1359dd1 100644 --- a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.html @@ -1,11 +1,11 @@ - -Control Hub - - - -
-
-
-
-

- + +Control Hub + + + +
+
+
+
+

+ diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js index e62bd0a..6f6686f 100644 --- a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js @@ -1,17 +1,46 @@ "use strict"; -let socket, context, currentSettings = {}, action; +let socket, context, 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 eller eksportér ikke profiler med token. En fejl kan betyde ukendt udfald; kontrollér status før nyt tryk.", save: "Gem", saved: "Gemt" }, - 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 or export profiles containing it. An error can mean an unknown outcome; check status before pressing again.", save: "Save", saved: "Saved" } + 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 language = el("language").value; - document.documentElement.lang = language; - for (const [id, value] of Object.entries(translations[language])) if (id !== "saved") el(id).textContent = value; + 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"; @@ -25,18 +54,34 @@ function connectElgatoStreamDeckSocket(port, uuid, registerEvent, info, actionIn 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 })); + socket.onopen = () => { socket.send(JSON.stringify({ event: registerEvent, uuid })); clearCheck(); }; + socket.onclose = () => { clearCheck(); el("connection").textContent = translations[language()].disconnected; }; socket.onmessage = event => { - const message = JSON.parse(event.data); - if (message.event === "didReceiveSettings") load(message.payload.settings); + let message; + try { message = JSON.parse(event.data); } catch { return; } + if (message.event === "didReceiveSettings" && message.context === context) load(message.payload.settings); + if (message.event === "sendToPropertyInspector" && message.context === context && + 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) return; - const settings = { ...currentSettings, token: el("token").value, language: el("language").value, + 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", 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/README.en.md b/README.en.md index 4b62a7b..9477b00 100644 --- a/README.en.md +++ b/README.en.md @@ -1,66 +1,66 @@ -# 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) -- [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 desktop GUI, service installer or persistent queue | -| 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 and status key | Source plugin for manual development installation; hardware acceptance pending | -| AndroidRemote | Plugin ID, status placeholder and integration plan | No Android app or pairing yet | -| 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 - -Requirements: .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 -``` - -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 -``` +# 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) +- [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 desktop GUI, service installer or persistent queue | +| 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 and status key | Source plugin for manual development installation; hardware acceptance pending | +| AndroidRemote | Plugin ID, status placeholder and integration plan | No Android app or pairing yet | +| 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 + +Requirements: .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 0cd0e02..da46c99 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,66 @@ -# 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) -- [Kommando- og statusprotokol](docs/protocol.da.md) · [English](docs/protocol.en.md) -- [Testplan og acceptkriterier](docs/testing.da.md) · [English](docs/testing.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 desktop-GUI, serviceinstallation eller vedvarende kø | -| 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 og statusknap | Kildeplugin til manuel udviklingsinstallation; endnu ikke hardwaregodkendt | -| AndroidRemote | Plugin-id, statuspladsholder og integrationsplan | Ingen Android-app eller parring endnu | -| 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 - -Krav: .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 -``` - -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 -``` +# 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) +- [Kommando- og statusprotokol](docs/protocol.da.md) · [English](docs/protocol.en.md) +- [Testplan og acceptkriterier](docs/testing.da.md) · [English](docs/testing.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 desktop-GUI, serviceinstallation eller vedvarende kø | +| 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 og statusknap | Kildeplugin til manuel udviklingsinstallation; endnu ikke hardwaregodkendt | +| AndroidRemote | Plugin-id, statuspladsholder og integrationsplan | Ingen Android-app eller parring endnu | +| 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 + +Krav: .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/docs/project.da.md b/docs/project.da.md index 806f8bd..ecde9a7 100644 --- a/docs/project.da.md +++ b/docs/project.da.md @@ -1,96 +1,98 @@ -# 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. - -En visuel desktopkontrolcentral, brugerprofiler, makroer, samlet scene-/slideautomatik og installation som Windows-service ligger 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 · planlagt"] -.->|"Fremtidig parret transport"| 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. - +# 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. + +En visuel desktopkontrolcentral, brugerprofiler, makroer, samlet scene-/slideautomatik og installation som Windows-service ligger 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 · planlagt"] -.->|"Fremtidig parret transport"| 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. -## 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ø. +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ø. diff --git a/docs/project.en.md b/docs/project.en.md index 8027164..c805200 100644 --- a/docs/project.en.md +++ b/docs/project.en.md @@ -1,96 +1,98 @@ -# 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 desktop control dashboard, user profiles, macros, combined scene/slide automation and Windows service installation are 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 · planned"] -.->|"Future paired transport"| 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. - +# 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 desktop control dashboard, user profiles, macros, combined scene/slide automation and Windows service installation are 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 · planned"] -.->|"Future paired transport"| 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. -## 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. +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. diff --git a/docs/setup.da.md b/docs/setup.da.md index 9f36a5c..11ea000 100644 --- a/docs/setup.da.md +++ b/docs/setup.da.md @@ -1,79 +1,80 @@ -# Installation og betjening - -[English](setup.en.md) · [Forside](../README.md) - -## Forudsætninger - -- 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 -node scripts/check-policy.cjs -``` - -`node tests/host-smoke.cjs` starter en kortvarig testhost på port 5187. Stop din normale host først. 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. 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. - -Dette er en manuel udviklingsinstallation fra kildekode. Der er ikke udgivet en Marketplace-pakke, installer, release eller 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. +# Installation og betjening + +[English](setup.en.md) · [Forside](../README.md) + +## Forudsætninger + +- 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å port 5187. Stop din normale host først. 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. + +Dette er en manuel udviklingsinstallation fra kildekode. Der er ikke udgivet en Marketplace-pakke, installer, release eller 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. diff --git a/docs/setup.en.md b/docs/setup.en.md index cfaf8c5..225efa0 100644 --- a/docs/setup.en.md +++ b/docs/setup.en.md @@ -1,79 +1,80 @@ -# Setup and operation - -[Dansk](setup.da.md) · [Home](../README.en.md) - -## Prerequisites - -- 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 -node scripts/check-policy.cjs -``` - -`node tests/host-smoke.cjs` starts a temporary test host on port 5187. Stop your normal host first. 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. Enter exact OBS scene and input names. Go-to requires a positive slide number. Mute specifies a desired state rather than blindly toggling. - -This is a manual development installation from source. No Marketplace package, installer, release or tag has been published. - -## 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. +# Setup and operation + +[Dansk](setup.da.md) · [Home](../README.en.md) + +## Prerequisites + +- 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 port 5187. Stop your normal host first. 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. + +This is a manual development installation from source. No Marketplace package, installer, release or tag has been published. + +## 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. diff --git a/docs/testing.da.md b/docs/testing.da.md index 6c4afc9..9ed1f5b 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -1,46 +1,49 @@ -# Testplan og accept - -[English](testing.en.md) - -## Automatiske kontroller - -- 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. -- 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ø. +# Testplan og accept + +[English](testing.en.md) + +## Automatiske kontroller + +- 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ø. diff --git a/docs/testing.en.md b/docs/testing.en.md index 2afe5c7..a2e5cc9 100644 --- a/docs/testing.en.md +++ b/docs/testing.en.md @@ -1,46 +1,49 @@ -# Test plan and acceptance - -[Dansk](testing.da.md) - -## Automated checks - -- 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. -- 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. +# Test plan and acceptance + +[Dansk](testing.da.md) + +## Automated checks + +- 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. diff --git a/tests/host-smoke.cjs b/tests/host-smoke.cjs index e8b3f81..cb41e02 100644 --- a/tests/host-smoke.cjs +++ b/tests/host-smoke.cjs @@ -1,41 +1,54 @@ -const assert = require("node:assert/strict"); -const { spawn } = require("node:child_process"); -const { randomBytes, randomUUID } = require("node:crypto"); -const token = randomBytes(32).toString("hex"); -const child = spawn("dotnet", ["src/ControlHub.Host/bin/Release/net10.0/ControlHub.Host.dll"], - { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); -let log = ""; -child.stdout.on("data", d => { log = (log + d).slice(-4000); }); -child.stderr.on("data", d => { log = (log + d).slice(-4000); }); -const base = "http://127.0.0.1:5187/api/v1/"; -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((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")); - 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,"not_implemented"); - assert.equal(status.plugins.find(p=>p.id==="obs").state,"unavailable"); - console.log("Host smoke checks passed / Host-kontrol bestået"); - } finally { child.kill(); } -})().catch(error=>{ console.error(error); process.exitCode=1; }); +const assert = require("node:assert/strict"); +const { spawn } = require("node:child_process"); +const { randomBytes, randomUUID } = require("node:crypto"); +const token = randomBytes(32).toString("hex"); +const child = spawn("dotnet", ["src/ControlHub.Host/bin/Release/net10.0/ControlHub.Host.dll"], + { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); +let log = ""; +child.stdout.on("data", d => { log = (log + d).slice(-4000); }); +child.stderr.on("data", d => { log = (log + d).slice(-4000); }); +const base = "http://127.0.0.1:5187/api/v1/"; +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((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")); + 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,"not_implemented"); + 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)); + 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..fb79694 --- /dev/null +++ b/tests/inspector.test.cjs @@ -0,0 +1,58 @@ +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,"key","registerPropertyInspector","{}",JSON.stringify({ + 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[1].payload.token,"new".repeat(20)); + assert.equal(ui.el("check").disabled,true); +}); +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/streamdeck.test.cjs b/tests/streamdeck.test.cjs index 491db98..f9d8903 100644 --- a/tests/streamdeck.test.cjs +++ b/tests/streamdeck.test.cjs @@ -1,88 +1,196 @@ -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 } } }); +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); +}); -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"))); +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("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 }) }; +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({ 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")); + 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("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("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("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 }) })); +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({ event:"keyDown", context:"key" }); - assert.ok(sent.some(m => m.event === "showAlert")); + 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("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("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("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" }); +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("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")); +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.poll(); + 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"); }); From a8d46ed818c2553509d2053e5211e0801d1c5ba3 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:55:33 +0100 Subject: [PATCH 03/10] =?UTF-8?q?Add=20bilingual=20Windows=20control=20win?= =?UTF-8?q?dow=20and=20development=20installers=20/=20Tilf=C3=B8j=20kontro?= =?UTF-8?q?lvindue=20og=20installationspakker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 14 ++ CHANGELOG.md | 6 + ControlHub.slnx | 27 +-- Plugins/StreamDeck/README.md | 22 +-- README.en.md | 9 +- README.md | 10 +- docs/installation.da.html | 13 ++ docs/installation.en.html | 13 ++ docs/project.da.md | 2 +- docs/project.en.md | 2 +- docs/references.md | 30 ++-- docs/setup.da.md | 15 +- docs/setup.en.md | 15 +- docs/testing.da.md | 2 + docs/testing.en.md | 2 + packaging/windows/ControlHub.iss | 60 +++++++ scripts/package-windows.ps1 | 43 +++++ scripts/verify-package.ps1 | 22 +++ .../ControlHub.Desktop.csproj | 9 + src/ControlHub.Desktop/HostSession.cs | 94 +++++++++++ src/ControlHub.Desktop/MainWindow.cs | 149 +++++++++++++++++ src/ControlHub.Desktop/PackageSelfTest.cs | 63 +++++++ src/ControlHub.Desktop/Program.cs | 24 +++ src/ControlHub.Desktop/Settings.cs | 51 ++++++ src/ControlHub.Host/Program.cs | 155 +++++++++--------- 25 files changed, 732 insertions(+), 120 deletions(-) create mode 100644 docs/installation.da.html create mode 100644 docs/installation.en.html create mode 100644 packaging/windows/ControlHub.iss create mode 100644 scripts/package-windows.ps1 create mode 100644 scripts/verify-package.ps1 create mode 100644 src/ControlHub.Desktop/ControlHub.Desktop.csproj create mode 100644 src/ControlHub.Desktop/HostSession.cs create mode 100644 src/ControlHub.Desktop/MainWindow.cs create mode 100644 src/ControlHub.Desktop/PackageSelfTest.cs create mode 100644 src/ControlHub.Desktop/Program.cs create mode 100644 src/ControlHub.Desktop/Settings.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef4c93c..6b7c689 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,3 +29,17 @@ jobs: - run: npx --yes --package=@elgato/cli@1.10.3 streamdeck validate --no-update-check Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin - run: node tests/host-smoke.cjs - run: node scripts/check-policy.cjs + - name: Build Windows installers / Byg Windows-installation + if: runner.os == 'Windows' + shell: pwsh + run: | + $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" + ./scripts/package-windows.ps1 -IsccPath $iscc -OutputDirectory "$env:GITHUB_WORKSPACE\artifacts\windows" + ./scripts/verify-package.ps1 -PackageDirectory "$env:GITHUB_WORKSPACE\artifacts\windows" + - uses: actions/upload-artifact@v4 + if: runner.os == 'Windows' + with: + name: ControlHub-0.0.001-windows-development + path: artifacts/windows/files/* + retention-days: 14 + if-no-files-found: error diff --git a/CHANGELOG.md b/CHANGELOG.md index e4eae60..e45b0c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ ## 0.0.001 — udviklingsversion / development version ### Dansk +- Windows x64-installation med inkluderet .NET og officiel Stream Deck-installationspakke. +- Dansk/engelsk kontrolvindue med start/stop, forbindelsesstatus, kopiering af vedvarende token og DPAPI-krypterede OBS-indstillinger. +- Pakketest af konfiguration, lokal host og stop; Windows-artefakter i CI uden release/tag. - Forbindelsestest i Stream Deck-indstillingerne med separat status for Control Hub, PowerPoint og OBS. - Beskyttelse mod forsinket knapfeedback efter profil-/indstillingsskift. - Hovedikon i krævet PNG-format og officiel Elgato-validering i CI. @@ -16,6 +19,9 @@ - Fysisk test i det aktive miljø afventer. Ingen release eller tag. ### English +- Windows x64 installer with included .NET and an official Stream Deck installation package. +- Danish/English control window with start/stop, connection status, persistent token copying and DPAPI-encrypted OBS settings. +- Package checks for configuration, local host and shutdown; Windows CI artifacts without a release/tag. - Connection check in Stream Deck settings with separate Control Hub, PowerPoint and OBS status. - Protection against late key feedback after profile/settings changes. - Main icon in the required PNG format and official Elgato validation in CI. diff --git a/ControlHub.slnx b/ControlHub.slnx index 3e3f2c4..e4ae363 100644 --- a/ControlHub.slnx +++ b/ControlHub.slnx @@ -1,13 +1,14 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/Plugins/StreamDeck/README.md b/Plugins/StreamDeck/README.md index bbff82c..680530b 100644 --- a/Plugins/StreamDeck/README.md +++ b/Plugins/StreamDeck/README.md @@ -1,11 +1,11 @@ -# StreamDeck - -## Dansk -Implementeret kildeplugin med 12 handlinger; installation og hardwaretest afventer. - -Se [installation](../../docs/setup.da.md), [arkitektur](../../docs/project.da.md), [protokol](../../docs/protocol.da.md) og [testplan](../../docs/testing.da.md). - -## English -Implemented source plugin with 12 actions; installation and hardware testing pending. - -See [setup](../../docs/setup.en.md), [architecture](../../docs/project.en.md), [protocol](../../docs/protocol.en.md) and [test plan](../../docs/testing.en.md). +# 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/README.en.md b/README.en.md index 9477b00..c676166 100644 --- a/README.en.md +++ b/README.en.md @@ -22,10 +22,11 @@ The goal is to give operators clear buttons, predictable commands and truthful s | Area | Implemented in 0.0.001 | Limitation | |---|---|---| -| C#/.NET 10 | Local HTTP host, validation, plugin registration, status, timeouts and bounded deduplication | No desktop GUI, service installer or persistent queue | +| 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 and status key | Source plugin for manual development installation; hardware acceptance pending | +| Stream Deck | 12 actions, Danish/English settings, result feedback, status key and installation package | Loading verified locally; complete hardware acceptance pending | | AndroidRemote | Plugin ID, status placeholder and integration plan | No Android app or pairing yet | | Audio, Logitech, Android Live, physical remote, Flux Keyboard | Directories, integration plans and status placeholders | No working device drivers yet | @@ -33,7 +34,9 @@ OBS audio control applies to named OBS inputs. The separate operating-system aud ## Quick start -Requirements: .NET 10 SDK; for the priority chain, Windows, desktop PowerPoint, OBS with WebSocket v5, and Stream Deck 7.4+. +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 diff --git a/README.md b/README.md index da46c99..13dee47 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og - [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) - [Versionsregler / Version policy](docs/versioning.md) @@ -22,10 +23,11 @@ Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og | Område | Implementeret i 0.0.001 | Begrænsning | |---|---|---| -| C#/.NET 10 | Lokal HTTP-host, validering, pluginregistrering, status, timeouts og begrænset dubletbeskyttelse | Ingen desktop-GUI, serviceinstallation eller vedvarende kø | +| 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 og statusknap | Kildeplugin til manuel udviklingsinstallation; endnu ikke hardwaregodkendt | +| Stream Deck | 12 handlinger, danske/engelske indstillinger, resultatfeedback, statusknap og installationspakke | Indlæsning verificeret lokalt; samlet hardwareaccept afventer | | AndroidRemote | Plugin-id, statuspladsholder og integrationsplan | Ingen Android-app eller parring endnu | | Lyd, Logitech, Android Live, fysisk fjernkontrol, Flux Keyboard | Mapper, integrationsplaner og statuspladsholdere | Ingen fungerende enhedsdrivere endnu | @@ -33,7 +35,9 @@ OBS-lydstyring gælder navngivne OBS-lydkilder. Det separate lydplugin til opera ## Hurtig start -Krav: .NET 10 SDK; til den prioriterede kæde Windows, PowerPoint desktop, OBS med WebSocket v5 og Stream Deck 7.4+. +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 diff --git a/docs/installation.da.html b/docs/installation.da.html new file mode 100644 index 0000000..ec9979c --- /dev/null +++ b/docs/installation.da.html @@ -0,0 +1,13 @@ +Control Hub – installation + +English

Control Hub 0.0.001

Installationsvejledning til Windows x64 · udviklingsversion

+

Stream Deck → PowerPoint og OBS er første prioritet. AndroidRemote og de øvrige enhedsintegrationer er endnu kun forberedt. Installationspakken er ikke en godkendelse af praktisk afvikling.

+

1. Installér

  1. Åbn ControlHub-0.0.001-win-x64-Setup.exe, og vælg Dansk. Programmet installeres for din Windows-bruger og har en almindelig afinstalleringsfunktion.
  2. .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.
  3. Å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

  1. Aktivér OBS' WebSocket-server i OBS, og aflæs port og adgangskode. Brug WebSocket-adgangskoden, ikke streamingnøglen.
  2. Indtast adressen, normalt ws://127.0.0.1:4455, og adgangskoden i Control Hub. Tryk Gem indstillinger.
  3. 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

  1. 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.
  2. 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.
  3. Træk Status, Næste slide, Forrige slide og Skift scene fra gruppen Control Hub til en testprofil.
  4. 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.
  5. 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.

+

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

  • 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..b594568 --- /dev/null +++ b/docs/installation.en.html @@ -0,0 +1,13 @@ +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 and the other device integrations are only planned. This installation package does not establish acceptance for live operation.

+

1. Install

  1. Open ControlHub-0.0.001-win-x64-Setup.exe and select English. It installs for your Windows user and includes a standard uninstaller.
  2. .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.
  3. 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

  1. Enable OBS' WebSocket server in OBS and check its port and password. Use the WebSocket password, not your streaming key.
  2. Enter the address, usually ws://127.0.0.1:4455, and password in Control Hub. Click Save settings.
  3. Click Start Control Hub. Status reports PowerPoint and OBS connectivity separately. Check connection only reads status.
+

3. Install the Stream Deck keys

  1. Click Install Stream Deck plugin in Control Hub and complete Stream Deck's installation dialog. Alternatively, double-click the included dk.thebonden.controlhub.streamDeckPlugin.
  2. 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.
  3. Drag Status, Next slide, Previous slide and Switch scene from the Control Hub group onto a test profile.
  4. 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.
  5. 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.

+

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

  • 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 index ecde9a7..42a2448 100644 --- a/docs/project.da.md +++ b/docs/project.da.md @@ -18,7 +18,7 @@ Et typisk forløb er, at operatøren åbner præsentationen, starter slideshowet 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. -En visuel desktopkontrolcentral, brugerprofiler, makroer, samlet scene-/slideautomatik og installation som Windows-service ligger uden for første version. Ingen tidsplan eller færdiggørelsesprocent udledes af versionsnummeret. +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 diff --git a/docs/project.en.md b/docs/project.en.md index c805200..b78bf6f 100644 --- a/docs/project.en.md +++ b/docs/project.en.md @@ -18,7 +18,7 @@ A typical workflow starts with the operator opening the presentation, starting t 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 desktop control dashboard, user profiles, macros, combined scene/slide automation and Windows service installation are outside the first version. The version number is not a schedule or a percentage-complete metric. +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 diff --git a/docs/references.md b/docs/references.md index cf97c3c..ffeafd0 100644 --- a/docs/references.md +++ b/docs/references.md @@ -1,13 +1,17 @@ -# 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/) - -Henvisninger beskriver API'er; de er ikke bevis for lokal hardwaretest. / References describe APIs; they are not evidence of local hardware testing. +# 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. diff --git a/docs/setup.da.md b/docs/setup.da.md index 11ea000..ed5837d 100644 --- a/docs/setup.da.md +++ b/docs/setup.da.md @@ -4,6 +4,8 @@ ## 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. @@ -51,7 +53,18 @@ API-adressen er fast `http://127.0.0.1:5187`. Hostens token skal kopieres privat 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. -Dette er en manuel udviklingsinstallation fra kildekode. Der er ikke udgivet en Marketplace-pakke, installer, release eller tag. +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 diff --git a/docs/setup.en.md b/docs/setup.en.md index 225efa0..d450235 100644 --- a/docs/setup.en.md +++ b/docs/setup.en.md @@ -4,6 +4,8 @@ ## 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. @@ -51,7 +53,18 @@ The API address is fixed at `http://127.0.0.1:5187`. Privately copy the host tok 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. -This is a manual development installation from source. No Marketplace package, installer, release or tag has been published. +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 diff --git a/docs/testing.da.md b/docs/testing.da.md index 9ed1f5b..eff0c73 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -4,6 +4,8 @@ ## 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. diff --git a/docs/testing.en.md b/docs/testing.en.md index a2e5cc9..dc0546f 100644 --- a/docs/testing.en.md +++ b/docs/testing.en.md @@ -4,6 +4,8 @@ ## 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. 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/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.Desktop/ControlHub.Desktop.csproj b/src/ControlHub.Desktop/ControlHub.Desktop.csproj new file mode 100644 index 0000000..23c0097 --- /dev/null +++ b/src/ControlHub.Desktop/ControlHub.Desktop.csproj @@ -0,0 +1,9 @@ + + + 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..0e65d6b --- /dev/null +++ b/src/ControlHub.Desktop/HostSession.cs @@ -0,0 +1,94 @@ +using System.Diagnostics; +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() { Timeout = TimeSpan.FromSeconds(35) }; + public bool IsRunning => process is { HasExited: false }; + + public async Task StartAsync(Settings settings) + { + settings.Validate(); + if (IsRunning) return; + using (var port = new TcpClient()) + { + try + { + await port.ConnectAsync(IPAddress.Loopback, 5187); + throw new InvalidOperationException("Port 5187 er optaget. Stop den anden host først. / Port 5187 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; + 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("http://127.0.0.1:5187/api/v1/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("http://127.0.0.1:5187/api/v1/status"); + response.EnsureSuccessStatusCode(); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } + + public async Task StopAsync() + { + 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..5108632 --- /dev/null +++ b/src/ControlHub.Desktop/MainWindow.cs @@ -0,0 +1,149 @@ +using System.Diagnostics; + +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 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 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(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); await ShowStatusAsync(); }); + stop.Click += async (_, _) => await RunAsync(async () => { await host.StopAsync(); ShowStoppedOrRunning(); }); + refresh.Click += async (_, _) => await RunAsync(ShowStatusAsync); + 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"); + 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; + start.Enabled = save.Enabled = obsUrl.Enabled = obsPassword.Enabled = !busy && !running; + stop.Enabled = refresh.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..b329c53 --- /dev/null +++ b/src/ControlHub.Desktop/PackageSelfTest.cs @@ -0,0 +1,63 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +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 host = new HostSession(); + await host.StartAsync(original); + 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"); + checks.Add("Published host starts; authenticated status works; test OBS is isolated"); + using var other = new HostSession(); + 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/Program.cs b/src/ControlHub.Host/Program.cs index 4b7af6d..d7c6af9 100644 --- a/src/ControlHub.Host/Program.cs +++ b/src/ControlHub.Host/Program.cs @@ -1,73 +1,82 @@ -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.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 builder = WebApplication.CreateBuilder(args); -builder.WebHost.ConfigureKestrel(options => -{ - options.Listen(IPAddress.Loopback, 5187); - 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 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 PlannedPlugin("androidremote", new("AndroidRemote", "AndroidRemote")), - 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(); -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(); -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"); -try { await app.RunAsync(); } -finally { foreach (var plugin in plugins) await plugin.DisposeAsync(); } +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.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 builder = WebApplication.CreateBuilder(args); +builder.WebHost.ConfigureKestrel(options => +{ + options.Listen(IPAddress.Loopback, 5187); + 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 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 PlannedPlugin("androidremote", new("AndroidRemote", "AndroidRemote")), + 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(); +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"); +try { await app.RunAsync(); } +finally { foreach (var plugin in plugins) await plugin.DisposeAsync(); } From 1bebf4c8799e4f7d6fbf44071a6ba7e4beb772e7 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:39:50 +0100 Subject: [PATCH 04/10] Fix Stream Deck inspector reply routing / Ret forbindelsessvar til Stream Deck-knappen --- CHANGELOG.md | 2 ++ .../inspector.js | 14 ++++++---- docs/testing.da.md | 8 ++++++ docs/testing.en.md | 8 ++++++ tests/inspector.test.cjs | 27 +++++++++++++++++-- 5 files changed, 52 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e45b0c6..67d2735 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.0.001 — udviklingsversion / development version ### Dansk +- Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. - Windows x64-installation med inkluderet .NET og officiel Stream Deck-installationspakke. - Dansk/engelsk kontrolvindue med start/stop, forbindelsesstatus, kopiering af vedvarende token og DPAPI-krypterede OBS-indstillinger. - Pakketest af konfiguration, lokal host og stop; Windows-artefakter i CI uden release/tag. @@ -19,6 +20,7 @@ - Fysisk test i det aktive miljø afventer. Ingen release eller tag. ### English +- Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. - Windows x64 installer with included .NET and an official Stream Deck installation package. - Danish/English control window with start/stop, connection status, persistent token copying and DPAPI-encrypted OBS settings. - Package checks for configuration, local host and shutdown; Windows CI artifacts without a release/tag. diff --git a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js index 6f6686f..b29171a 100644 --- a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/inspector.js @@ -1,5 +1,5 @@ "use strict"; -let socket, context, currentSettings = {}, action, pendingCheck = null, checkTimer, lastReport = null; +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", @@ -48,7 +48,10 @@ function load(settings) { } function connectElgatoStreamDeckSocket(port, uuid, registerEvent, info, actionInfo) { const data = JSON.parse(actionInfo); - context = uuid; action = data.action; + // 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"); @@ -59,8 +62,9 @@ function connectElgatoStreamDeckSocket(port, uuid, registerEvent, info, actionIn socket.onmessage = event => { let message; try { message = JSON.parse(event.data); } catch { return; } - if (message.event === "didReceiveSettings" && message.context === context) load(message.payload.settings); - if (message.event === "sendToPropertyInspector" && message.context === context && + 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(); } @@ -72,7 +76,7 @@ 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", context, payload: settings })); + socket.send(JSON.stringify({ event: "setSettings", action, context, payload: settings })); el("saved").textContent = translations[settings.language].saved; }; el("check").onclick = () => { diff --git a/docs/testing.da.md b/docs/testing.da.md index eff0c73..c5ef196 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -49,3 +49,11 @@ Beregn filhash med `Get-FileHash -Algorithm SHA256 -LiteralPath ''` before and a 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 — 31 October 2026 + +Stream Deck previously loaded all 12 actions. A configured status key received authenticated status from Control Hub while PowerPoint and OBS appeared unavailable. This verifies status connectivity, but not physical key presses or application control. + +Testing exposed different IDs for the inspector registration and its key. The connection check sent correctly but ignored the reply addressed to the key. The fix preserves the sender ID and accepts the reply for the associated key. A regression test covers the round trip through the plugin bridge with simulated Stream Deck routing. 25 JavaScript tests pass. The corrected dialog still requires a live Stream Deck check. + +When work resumed on 31 October, Stream Deck, OBS, Control Hub and PowerPoint were not open. Automatic launch through app control failed. No new practical PowerPoint/OBS test or completed hardware acceptance is therefore recorded. No presentation files were changed and no recording or streaming was started. diff --git a/tests/inspector.test.cjs b/tests/inspector.test.cjs index fb79694..ff2aa54 100644 --- a/tests/inspector.test.cjs +++ b/tests/inspector.test.cjs @@ -17,8 +17,8 @@ function inspector(language="da") { 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,"key","registerPropertyInspector","{}",JSON.stringify({ - action:"dk.thebonden.controlhub.next",payload:{settings:{language,token:"t".repeat(40)}}})); + 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?.()}; } @@ -28,9 +28,32 @@ test("inspector connection check sends no command and does not save credentials" 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:[]}; From 1a371b9e6469e4005d41143f265bf5faa8c27869 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:15:10 +0100 Subject: [PATCH 05/10] Explain PowerPoint and OBS connection failures / Forklar forbindelsesfejl og ukendte OBS-udfald --- CHANGELOG.md | 4 + Plugins/Obs/ObsClient.cs | 66 ++-- Plugins/Obs/ObsFailure.cs | 42 +++ Plugins/Obs/ObsPlugin.cs | 25 +- Plugins/PowerPoint/ComSlideShowSession.cs | 201 ++++++------ Plugins/PowerPoint/PowerPointPlugin.cs | 167 +++++----- .../diagnostics.js | 25 +- docs/installation.da.html | 2 +- docs/installation.en.html | 2 +- docs/protocol.da.md | 163 +++++----- docs/protocol.en.md | 163 +++++----- docs/testing.da.md | 10 +- docs/testing.en.md | 10 +- tests/ControlHub.Tests/ObsTransportTests.cs | 288 +++++++++++------- tests/ControlHub.Tests/PluginTests.cs | 279 +++++++++-------- tests/streamdeck.test.cjs | 28 ++ 16 files changed, 878 insertions(+), 597 deletions(-) create mode 100644 Plugins/Obs/ObsFailure.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 67d2735..94c355a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ## 0.0.001 — udviklingsversion / development version ### Dansk +- Konkrete forbindelsesårsager for PowerPoint og OBS i status og Stream Deck, med sikre dansk/engelske tekster. +- Afbrudte OBS-kommandoer efter påbegyndt afsendelse rapporteres som ukendt udfald; aldrig automatisk genafsendelse. - Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. - Windows x64-installation med inkluderet .NET og officiel Stream Deck-installationspakke. - Dansk/engelsk kontrolvindue med start/stop, forbindelsesstatus, kopiering af vedvarende token og DPAPI-krypterede OBS-indstillinger. @@ -20,6 +22,8 @@ - Fysisk test i det aktive miljø afventer. Ingen release eller tag. ### English +- Specific PowerPoint/OBS connection reasons in status and Stream Deck, with safe Danish/English messages. +- OBS commands interrupted after transmission starts report an unknown outcome; no automatic retries. - Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. - Windows x64 installer with included .NET and an official Stream Deck installation package. - Danish/English control window with start/stop, connection status, persistent token copying and DPAPI-encrypted OBS settings. diff --git a/Plugins/Obs/ObsClient.cs b/Plugins/Obs/ObsClient.cs index 6c3eaec..448b5b6 100644 --- a/Plugins/Obs/ObsClient.cs +++ b/Plugins/Obs/ObsClient.cs @@ -11,7 +11,6 @@ public interface IObsClient Task RequestAsync(string requestType, object requestData, CancellationToken cancellationToken); } -public sealed class ObsRequestException : Exception; public sealed class ObsClient : IObsClient { private readonly Uri endpoint; @@ -34,31 +33,48 @@ public static string Authenticate(string password, string salt, string challenge public async Task RequestAsync(string requestType, object requestData, CancellationToken cancellationToken) { using var socket = new ClientWebSocket(); - await socket.ConnectAsync(endpoint, cancellationToken); - var hello = await ReceiveAsync(socket, cancellationToken); - if (hello.GetProperty("op").GetInt32() != 0) throw new ObsRequestException(); - var identify = new Dictionary { ["rpcVersion"] = 1, ["eventSubscriptions"] = 0 }; - if (hello.GetProperty("d").TryGetProperty("authentication", out var auth)) + var requestStarted = false; + try { - if (string.IsNullOrEmpty(password)) throw new ObsRequestException(); - identify["authentication"] = Authenticate(password, auth.GetProperty("salt").GetString()!, auth.GetProperty("challenge").GetString()!); + await socket.ConnectAsync(endpoint, cancellationToken); + var hello = await ReceiveAsync(socket, cancellationToken); + if (hello.GetProperty("op").GetInt32() != 0) throw new ObsRequestException(ObsFailure.ProtocolError); + var identify = new Dictionary { ["rpcVersion"] = 1, ["eventSubscriptions"] = 0 }; + if (hello.GetProperty("d").TryGetProperty("authentication", out var auth)) + { + if (string.IsNullOrEmpty(password)) throw new ObsRequestException(ObsFailure.PasswordMissing); + identify["authentication"] = Authenticate(password, auth.GetProperty("salt").GetString()!, auth.GetProperty("challenge").GetString()!); + } + await SendAsync(socket, new { op = 1, d = identify }, cancellationToken); + var identified = await ReceiveAsync(socket, cancellationToken); + if (identified.GetProperty("op").GetInt32() != 2 || + identified.GetProperty("d").GetProperty("negotiatedRpcVersion").GetInt32() != 1) throw new ObsRequestException(ObsFailure.ProtocolError); + var requestId = Guid.NewGuid().ToString("D"); + requestStarted = true; + await SendAsync(socket, new { op = 6, d = new { requestType, requestId, requestData } }, cancellationToken); + while (true) + { + var response = await ReceiveAsync(socket, cancellationToken); + if (response.GetProperty("op").GetInt32() == 5) continue; + if (response.GetProperty("op").GetInt32() != 7) throw new ObsRequestException(ObsFailure.ProtocolError); + var data = response.GetProperty("d"); + if (data.GetProperty("requestId").GetString() != requestId || + data.GetProperty("requestType").GetString() != requestType) throw new ObsRequestException(ObsFailure.ProtocolError); + if (!data.GetProperty("requestStatus").GetProperty("result").GetBoolean()) throw new ObsRequestException(); + return data.TryGetProperty("responseData", out var body) ? body.Clone() : null; + } } - await SendAsync(socket, new { op = 1, d = identify }, cancellationToken); - var identified = await ReceiveAsync(socket, cancellationToken); - if (identified.GetProperty("op").GetInt32() != 2 || - identified.GetProperty("d").GetProperty("negotiatedRpcVersion").GetInt32() != 1) throw new ObsRequestException(); - var requestId = Guid.NewGuid().ToString("D"); - await SendAsync(socket, new { op = 6, d = new { requestType, requestId, requestData } }, cancellationToken); - while (true) + catch (ObsRequestException error) when (requestStarted && error.Reason != ObsFailure.RequestRejected) { - var response = await ReceiveAsync(socket, cancellationToken); - if (response.GetProperty("op").GetInt32() == 5) continue; - if (response.GetProperty("op").GetInt32() != 7) throw new ObsRequestException(); - var data = response.GetProperty("d"); - if (data.GetProperty("requestId").GetString() != requestId || - data.GetProperty("requestType").GetString() != requestType) throw new ObsRequestException(); - if (!data.GetProperty("requestStatus").GetProperty("result").GetBoolean()) throw new ObsRequestException(); - return data.TryGetProperty("responseData", out var body) ? body.Clone() : null; + throw new ObsRequestException(error.Reason, outcomeUnknown: true); + } + catch (WebSocketException) + { + throw new ObsRequestException(requestStarted ? ObsFailure.ConnectionLost : ObsFailure.ConnectionUnavailable, requestStarted); + } + catch (Exception error) when (error is JsonException or KeyNotFoundException or InvalidOperationException or FormatException) + { + throw new ObsRequestException(ObsFailure.ProtocolError, requestStarted); } } @@ -74,8 +90,10 @@ private static async Task ReceiveAsync(WebSocket socket, Cancellati do { result = await socket.ReceiveAsync(new ArraySegment(buffer), cancellationToken); + if (result.MessageType == WebSocketMessageType.Close) + throw new ObsRequestException((int?)result.CloseStatus == 4009 ? ObsFailure.AuthenticationFailed : ObsFailure.ConnectionLost); if (result.MessageType != WebSocketMessageType.Text || stream.Length + result.Count > 1_048_576) - throw new ObsRequestException(); + throw new ObsRequestException(ObsFailure.ProtocolError); stream.Write(buffer, 0, result.Count); } while (!result.EndOfMessage); using var document = JsonDocument.Parse(stream.ToArray(), new JsonDocumentOptions { MaxDepth = 32 }); diff --git a/Plugins/Obs/ObsFailure.cs b/Plugins/Obs/ObsFailure.cs new file mode 100644 index 0000000..f4ba64b --- /dev/null +++ b/Plugins/Obs/ObsFailure.cs @@ -0,0 +1,42 @@ +using ControlHub.Contracts; + +namespace ControlHub.Plugins.Obs; + +public enum ObsFailure { RequestRejected, ConnectionUnavailable, PasswordMissing, AuthenticationFailed, ProtocolError, ConnectionLost } + +public sealed class ObsRequestException(ObsFailure reason = ObsFailure.RequestRejected, bool outcomeUnknown = false) : Exception +{ + public ObsFailure Reason { get; } = reason; + public bool OutcomeUnknown { get; } = outcomeUnknown; +} + +internal static class ObsFailureInfo +{ + public static string Code(ObsFailure reason) => reason switch + { + ObsFailure.ConnectionUnavailable => "connection_unavailable", + ObsFailure.PasswordMissing => "password_missing", + ObsFailure.AuthenticationFailed => "authentication_failed", + ObsFailure.ProtocolError => "protocol_error", + ObsFailure.ConnectionLost => "connection_lost", + _ => "request_rejected" + }; + + // Kun faste beskeder; aldrig serverens fejltekst eller adgangskode. + // Fixed messages only; never server-provided error text or credentials. + public static LocalizedText Message(ObsFailure reason) => reason switch + { + ObsFailure.ConnectionUnavailable => new("Kan ikke forbinde til OBS. Start OBS, aktivér WebSocket-serveren, og kontrollér porten.", + "Cannot connect to OBS. Start OBS, enable its WebSocket server and check the port."), + ObsFailure.PasswordMissing => new("OBS kræver en adgangskode. Indtast den i Control Hub, og start forbindelsen igen.", + "OBS requires a password. Enter it in Control Hub and restart the connection."), + ObsFailure.AuthenticationFailed => new("OBS afviste adgangskoden. Kontrollér den i Control Hub, og start forbindelsen igen.", + "OBS rejected the password. Check it in Control Hub and restart the connection."), + ObsFailure.ProtocolError => new("Svaret var ikke kompatibelt med OBS WebSocket v5. Kontrollér server og port.", + "The reply was not compatible with OBS WebSocket v5. Check the server and port."), + ObsFailure.ConnectionLost => new("OBS-forbindelsen blev afbrudt. Kontrollér status før en ny handling.", + "The OBS connection was interrupted. Check status before another action."), + _ => new("OBS afviste handlingen. Kontrollér scenenavn, lydkilde og aktuel status.", + "OBS rejected the request. Check the scene name, audio input and current status.") + }; +} diff --git a/Plugins/Obs/ObsPlugin.cs b/Plugins/Obs/ObsPlugin.cs index 01f7200..0d9c831 100644 --- a/Plugins/Obs/ObsPlugin.cs +++ b/Plugins/Obs/ObsPlugin.cs @@ -35,20 +35,31 @@ mute.ValueKind is not (System.Text.Json.JsonValueKind.True or System.Text.Json.J await client.RequestAsync(request, data, cancellationToken); return Wire.Result(command, true, "ok", "OBS bekræftede handlingen.", "OBS acknowledged the action."); } - catch (ObsRequestException) + catch (ObsRequestException error) { - return Wire.Result(command, false, "obs_rejected", "OBS-forbindelse eller handling afvist. Kontrollér status.", - "OBS connection or request rejected. Check status."); + var message = error.OutcomeUnknown + ? new LocalizedText("OBS-handlingens udfald er ukendt. Kontrollér status før en ny handling.", + "The OBS action's outcome is unknown. Check status before another action.") + : ObsFailureInfo.Message(error.Reason); + return Wire.Result(command, false, error.OutcomeUnknown ? "outcome_unknown" : "obs_rejected", message.Da, message.En, + new { reason = ObsFailureInfo.Code(error.Reason) }); } } private static CommandResult Invalid(Command command) => Wire.Result(command, false, "invalid_arguments", "Ugyldige OBS-argumenter.", "Invalid OBS arguments."); public async ValueTask GetStatusAsync(CancellationToken cancellationToken) { - var scene = await client.RequestAsync("GetCurrentProgramScene", new { }, cancellationToken); - var recording = await client.RequestAsync("GetRecordStatus", new { }, cancellationToken); - var streaming = await client.RequestAsync("GetStreamStatus", new { }, cancellationToken); - return new("obs", "ready", new("OBS tilsluttet.", "OBS connected."), Wire.Data(new { scene, recording, streaming })); + try + { + var scene = await client.RequestAsync("GetCurrentProgramScene", new { }, cancellationToken); + var recording = await client.RequestAsync("GetRecordStatus", new { }, cancellationToken); + var streaming = await client.RequestAsync("GetStreamStatus", new { }, cancellationToken); + return new("obs", "ready", new("OBS tilsluttet.", "OBS connected."), Wire.Data(new { scene, recording, streaming })); + } + catch (ObsRequestException error) + { + return new("obs", "unavailable", ObsFailureInfo.Message(error.Reason), Wire.Data(new { reason = ObsFailureInfo.Code(error.Reason) })); + } } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } diff --git a/Plugins/PowerPoint/ComSlideShowSession.cs b/Plugins/PowerPoint/ComSlideShowSession.cs index b1821b3..287f0b1 100644 --- a/Plugins/PowerPoint/ComSlideShowSession.cs +++ b/Plugins/PowerPoint/ComSlideShowSession.cs @@ -1,97 +1,104 @@ -using System.Collections.Concurrent; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; - -namespace ControlHub.Plugins.PowerPoint; - -[SupportedOSPlatform("windows")] -public sealed class ComSlideShowSession : ISlideShowSession -{ - private readonly BlockingCollection queue = new(); - private readonly Thread thread; - private int disposed; - public ComSlideShowSession() - { - thread = new Thread(() => { foreach (var action in queue.GetConsumingEnumerable()) action(); }) - { IsBackground = true, Name = "ControlHub.PowerPoint.STA" }; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - } - - private async Task InvokeAsync(Func action, CancellationToken cancellationToken) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this); - var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - queue.Add(() => - { - if (cancellationToken.IsCancellationRequested) { completion.TrySetCanceled(cancellationToken); return; } - try { completion.TrySetResult(action()); } - catch (Exception ex) { completion.TrySetException(ex); } - }, cancellationToken); - // COM cannot be forcibly cancelled; the client must reconcile an unknown result. - // COM kan ikke tvangsafbrydes; klienten skal kontrollere status efter timeout. - return await completion.Task.WaitAsync(cancellationToken); - } - - public Task ReadAsync(CancellationToken cancellationToken) - => InvokeAsync(() => WithView((view, count) => new SlideShowSnapshot((int)view.CurrentShowPosition, count, (int)view.State)), cancellationToken); - - public async Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken) - { - await InvokeAsync(() => WithView((view, count) => - { - cancellationToken.ThrowIfCancellationRequested(); - switch (action) - { - case "next": view.Next(); break; - case "previous": view.Previous(); break; - case "goto": - if (slide is null || slide < 1 || slide > count) throw new ArgumentOutOfRangeException(nameof(slide)); - view.GotoSlide(slide.Value, -1); break; - case "black": view.State = 3; break; - case "resume": view.State = 1; break; - default: throw new ArgumentException("Unknown action / Ukendt handling.", nameof(action)); - } - return true; - }), cancellationToken); - } - - private static T WithView(Func action) - { - var objects = new List(); - object Track(object value) { objects.Add(value); return value; } - try - { - var clsid = new Guid("91493441-5A91-11CF-8700-00AA0060263B"); - GetActiveObject(ref clsid, IntPtr.Zero, out var active); - dynamic app = Track(active); - dynamic windows = Track(app.SlideShowWindows); - if ((int)windows.Count != 1) throw new SlideShowUnavailableException(); - dynamic window = Track(windows.Item(1)); - dynamic presentation = Track(window.Presentation); - dynamic slides = Track(presentation.Slides); - dynamic view = Track(window.View); - return action(view, (int)slides.Count); - } - catch (COMException) { throw new SlideShowUnavailableException(); } - finally - { - for (var i = objects.Count - 1; i >= 0; i--) - if (Marshal.IsComObject(objects[i])) Marshal.ReleaseComObject(objects[i]); - } - } - - [DllImport("oleaut32.dll", PreserveSig = false)] - private static extern void GetActiveObject(ref Guid clsid, IntPtr reserved, - [MarshalAs(UnmanagedType.IUnknown)] out object result); - - public ValueTask DisposeAsync() - { - if (Interlocked.Exchange(ref disposed, 1) == 0) - { - queue.CompleteAdding(); - thread.Join(TimeSpan.FromSeconds(2)); - } - return ValueTask.CompletedTask; - } -} +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace ControlHub.Plugins.PowerPoint; + +[SupportedOSPlatform("windows")] +public sealed class ComSlideShowSession : ISlideShowSession +{ + private readonly BlockingCollection queue = new(); + private readonly Thread thread; + private int disposed; + public ComSlideShowSession() + { + thread = new Thread(() => { foreach (var action in queue.GetConsumingEnumerable()) action(); }) + { IsBackground = true, Name = "ControlHub.PowerPoint.STA" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + private async Task InvokeAsync(Func action, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.Add(() => + { + if (cancellationToken.IsCancellationRequested) { completion.TrySetCanceled(cancellationToken); return; } + try { completion.TrySetResult(action()); } + catch (Exception ex) { completion.TrySetException(ex); } + }, cancellationToken); + // COM cannot be forcibly cancelled; the client must reconcile an unknown result. + // COM kan ikke tvangsafbrydes; klienten skal kontrollere status efter timeout. + return await completion.Task.WaitAsync(cancellationToken); + } + + public Task ReadAsync(CancellationToken cancellationToken) + => InvokeAsync(() => WithView((view, count) => new SlideShowSnapshot((int)view.CurrentShowPosition, count, (int)view.State)), cancellationToken); + + public async Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken) + { + await InvokeAsync(() => WithView((view, count) => + { + cancellationToken.ThrowIfCancellationRequested(); + switch (action) + { + case "next": view.Next(); break; + case "previous": view.Previous(); break; + case "goto": + if (slide is null || slide < 1 || slide > count) throw new ArgumentOutOfRangeException(nameof(slide)); + view.GotoSlide(slide.Value, -1); break; + case "black": view.State = 3; break; + case "resume": view.State = 1; break; + default: throw new ArgumentException("Unknown action / Ukendt handling.", nameof(action)); + } + return true; + }), cancellationToken); + } + + private static T WithView(Func action) + { + var objects = new List(); + object Track(object value) { objects.Add(value); return value; } + try + { + var clsid = new Guid("91493441-5A91-11CF-8700-00AA0060263B"); + object active; + try { GetActiveObject(ref clsid, IntPtr.Zero, out active); } + catch (COMException error) when (error.HResult == unchecked((int)0x800401E3)) + { + throw new SlideShowUnavailableException(SlideShowFailure.NotRegistered); + } + dynamic app = Track(active); + dynamic windows = Track(app.SlideShowWindows); + var windowCount = (int)windows.Count; + if (windowCount == 0) throw new SlideShowUnavailableException(SlideShowFailure.NoSlideshow); + if (windowCount != 1) throw new SlideShowUnavailableException(SlideShowFailure.MultipleSlideshows); + dynamic window = Track(windows.Item(1)); + dynamic presentation = Track(window.Presentation); + dynamic slides = Track(presentation.Slides); + dynamic view = Track(window.View); + return action(view, (int)slides.Count); + } + catch (COMException) { throw new SlideShowUnavailableException(); } + finally + { + for (var i = objects.Count - 1; i >= 0; i--) + if (Marshal.IsComObject(objects[i])) Marshal.ReleaseComObject(objects[i]); + } + } + + [DllImport("oleaut32.dll", PreserveSig = false)] + private static extern void GetActiveObject(ref Guid clsid, IntPtr reserved, + [MarshalAs(UnmanagedType.IUnknown)] out object result); + + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref disposed, 1) == 0) + { + queue.CompleteAdding(); + thread.Join(TimeSpan.FromSeconds(2)); + } + return ValueTask.CompletedTask; + } +} diff --git a/Plugins/PowerPoint/PowerPointPlugin.cs b/Plugins/PowerPoint/PowerPointPlugin.cs index c27aef3..665e257 100644 --- a/Plugins/PowerPoint/PowerPointPlugin.cs +++ b/Plugins/PowerPoint/PowerPointPlugin.cs @@ -1,71 +1,96 @@ -using ControlHub.Contracts; - -namespace ControlHub.Plugins.PowerPoint; - -public sealed record SlideShowSnapshot(int Position, int SlideCount, int State); -public interface ISlideShowSession : IAsyncDisposable -{ - Task ReadAsync(CancellationToken cancellationToken); - Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken); -} - -public sealed class PowerPointPlugin : IHubPlugin -{ - private readonly ISlideShowSession? session; - public PluginDescriptor Descriptor { get; } = new("powerpoint", new("PowerPoint", "PowerPoint"), "experimental", - ["next", "previous", "goto", "black", "resume"]); - public PowerPointPlugin(ISlideShowSession? session = null) - { - this.session = session ?? (OperatingSystem.IsWindows() ? new ComSlideShowSession() : null); - } - - public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) - { - if (!Descriptor.Actions.Contains(command.Action)) - return Wire.Result(command, false, "unsupported_action", "Ukendt handling.", "Unknown action."); - int? slide = null; - if (command.Action == "goto") - { - if (!Wire.OnlyArguments(command.Arguments, "slide") || - !command.Arguments.TryGetProperty("slide", out var element) || - element.ValueKind != System.Text.Json.JsonValueKind.Number || !element.TryGetInt32(out var number) || number < 1) - return Wire.Result(command, false, "invalid_arguments", "Slide skal være et positivt heltal.", "Slide must be a positive integer."); - slide = number; - } - else if (!Wire.OnlyArguments(command.Arguments)) - return Wire.Result(command, false, "invalid_arguments", "Handlingen tager ingen argumenter.", "This action takes no arguments."); - if (session is null) - return Wire.Result(command, false, "unsupported_platform", "PowerPoint COM kræver Windows.", "PowerPoint COM requires Windows."); - try - { - await session.ApplyAsync(command.Action, slide, cancellationToken); - return Wire.Result(command, true, "ok", "Slideshow-kommando udført.", "Slideshow command completed."); - } - catch (SlideShowUnavailableException) - { - return Wire.Result(command, false, "slideshow_unavailable", - "Start præcis ét PowerPoint-slideshow manuelt.", "Start exactly one PowerPoint slideshow manually."); - } - catch (ArgumentOutOfRangeException) - { - return Wire.Result(command, false, "invalid_arguments", "Slide ligger uden for præsentationen.", "Slide is outside the presentation."); - } - } - - public async ValueTask 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) - { - return new("powerpoint", "unavailable", new("Intet entydigt slideshow.", "No unambiguous slideshow.")); - } - } - - public ValueTask DisposeAsync() => session?.DisposeAsync() ?? ValueTask.CompletedTask; -} -public sealed class SlideShowUnavailableException : Exception; +using ControlHub.Contracts; + +namespace ControlHub.Plugins.PowerPoint; + +public sealed record SlideShowSnapshot(int Position, int SlideCount, int State); +public interface ISlideShowSession : IAsyncDisposable +{ + Task ReadAsync(CancellationToken cancellationToken); + Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken); +} + +public sealed class PowerPointPlugin : IHubPlugin +{ + private readonly ISlideShowSession? session; + public PluginDescriptor Descriptor { get; } = new("powerpoint", new("PowerPoint", "PowerPoint"), "experimental", + ["next", "previous", "goto", "black", "resume"]); + public PowerPointPlugin(ISlideShowSession? session = null) + { + this.session = session ?? (OperatingSystem.IsWindows() ? new ComSlideShowSession() : null); + } + + public async ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) + { + if (!Descriptor.Actions.Contains(command.Action)) + return Wire.Result(command, false, "unsupported_action", "Ukendt handling.", "Unknown action."); + int? slide = null; + if (command.Action == "goto") + { + if (!Wire.OnlyArguments(command.Arguments, "slide") || + !command.Arguments.TryGetProperty("slide", out var element) || + element.ValueKind != System.Text.Json.JsonValueKind.Number || !element.TryGetInt32(out var number) || number < 1) + return Wire.Result(command, false, "invalid_arguments", "Slide skal være et positivt heltal.", "Slide must be a positive integer."); + slide = number; + } + else if (!Wire.OnlyArguments(command.Arguments)) + return Wire.Result(command, false, "invalid_arguments", "Handlingen tager ingen argumenter.", "This action takes no arguments."); + if (session is null) + return Wire.Result(command, false, "unsupported_platform", "PowerPoint COM kræver Windows.", "PowerPoint COM requires Windows."); + try + { + await session.ApplyAsync(command.Action, slide, cancellationToken); + return Wire.Result(command, true, "ok", "Slideshow-kommando udført.", "Slideshow command completed."); + } + catch (SlideShowUnavailableException error) + { + var message = FailureMessage(error.Reason); + return Wire.Result(command, false, "slideshow_unavailable", + message.Da, message.En, new { reason = FailureCode(error.Reason) }); + } + catch (ArgumentOutOfRangeException) + { + return Wire.Result(command, false, "invalid_arguments", "Slide ligger uden for præsentationen.", "Slide is outside the presentation."); + } + } + + public async ValueTask 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/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js index 456c7b6..a10f108 100644 --- a/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js +++ b/Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin/diagnostics.js @@ -1,4 +1,22 @@ "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."], @@ -21,11 +39,16 @@ function connectionReport(status) { return failure("invalid_response"); const state = matches[0].state; const ready = state === "ready"; - const message = id === "powerpoint" ? + 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"); diff --git a/docs/installation.da.html b/docs/installation.da.html index ec9979c..b51ebe0 100644 --- a/docs/installation.da.html +++ b/docs/installation.da.html @@ -9,5 +9,5 @@

3. Installér Stream Deck-knapperne

  1. Tryk Installér Stre

    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.

    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

    • 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.
    +

    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 index b594568..e151610 100644 --- a/docs/installation.en.html +++ b/docs/installation.en.html @@ -9,5 +9,5 @@

    3. Install the Stream Deck keys

    1. Click Install Stream Dec

      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.

      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

      • 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.
      +

      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/protocol.da.md b/docs/protocol.da.md index 635bdd6..ae112d6 100644 --- a/docs/protocol.da.md +++ b/docs/protocol.da.md @@ -1,78 +1,89 @@ -# 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 | +# 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 | |---|---| -| 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`. +| PowerPoint | `powerpoint_not_found`, `no_slideshow`, `multiple_slideshows`, `powerpoint_unavailable` | +| OBS | `connection_unavailable`, `password_missing`, `authentication_failed`, `protocol_error`, `connection_lost`, `request_rejected` | -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. +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. diff --git a/docs/protocol.en.md b/docs/protocol.en.md index ec8cb30..1ac7331 100644 --- a/docs/protocol.en.md +++ b/docs/protocol.en.md @@ -1,78 +1,89 @@ -# 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 | +# 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 | |---|---| -| 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`. +| PowerPoint | `powerpoint_not_found`, `no_slideshow`, `multiple_slideshows`, `powerpoint_unavailable` | +| OBS | `connection_unavailable`, `password_missing`, `authentication_failed`, `protocol_error`, `connection_lost`, `request_rejected` | -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. +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. diff --git a/docs/testing.da.md b/docs/testing.da.md index c5ef196..1ad7a8b 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -50,10 +50,12 @@ For hvert testforløb registreres dato, Windows/Office/OBS/Stream Deck-versioner 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 — 31. oktober 2026 +## Lokal integrationsstatus — opdateret 1. november 2026 -Stream Deck har tidligere indlæst alle 12 handlinger. En konfigureret statusknap modtog autentificeret status fra Control Hub, mens PowerPoint og OBS blev vist som utilgængelige. Dette bekræfter statusforbindelsen, men ikke fysisk knaptryk eller styring af programmerne. +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. -Afprøvningen afslørede, at indstillingsvinduets registrerings-id og knappens id er forskellige. Forbindelsestesten sendte korrekt, men ignorerede svaret til knappens id. Rettelsen bevarer afsender-id’et og accepterer svaret til den tilknyttede knap. En regressionstest dækker hele forløbet gennem pluginets bro med simuleret Stream Deck-routing. 25 JavaScript-tests består. Den rettede dialog skal stadig afprøves i Stream Deck. +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. -Ved genoptagelse den 31. oktober var Stream Deck, OBS, Control Hub og PowerPoint ikke åbne. Automatisk åbning via appstyringen fejlede. Der er derfor ikke registreret en ny praktisk PowerPoint-/OBS-test eller en gennemført hardwareaccept. Ingen præsentationsfiler er ændret, og ingen udsendelse eller optagelse er startet. +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. diff --git a/docs/testing.en.md b/docs/testing.en.md index 7f94a2c..3f4b01c 100644 --- a/docs/testing.en.md +++ b/docs/testing.en.md @@ -50,10 +50,12 @@ Record date, Windows/Office/OBS/Stream Deck versions, hardware model, plugin com 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 — 31 October 2026 +## Local integration status — updated 1 November 2026 -Stream Deck previously loaded all 12 actions. A configured status key received authenticated status from Control Hub while PowerPoint and OBS appeared unavailable. This verifies status connectivity, but not physical key presses or application control. +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. -Testing exposed different IDs for the inspector registration and its key. The connection check sent correctly but ignored the reply addressed to the key. The fix preserves the sender ID and accepts the reply for the associated key. A regression test covers the round trip through the plugin bridge with simulated Stream Deck routing. 25 JavaScript tests pass. The corrected dialog still requires a live Stream Deck check. +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. -When work resumed on 31 October, Stream Deck, OBS, Control Hub and PowerPoint were not open. Automatic launch through app control failed. No new practical PowerPoint/OBS test or completed hardware acceptance is therefore recorded. No presentation files were changed and no recording or streaming was started. +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. diff --git a/tests/ControlHub.Tests/ObsTransportTests.cs b/tests/ControlHub.Tests/ObsTransportTests.cs index 5f243ca..eaf2fa4 100644 --- a/tests/ControlHub.Tests/ObsTransportTests.cs +++ b/tests/ControlHub.Tests/ObsTransportTests.cs @@ -1,106 +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)); - await Assert.ThrowsAsync(() => - new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token)); - } - - [Fact] - public async Task MissingPasswordFailsBeforeSendingCommand() - { - await using var server = await FakeServer.StartAsync(true); - using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - await Assert.ThrowsAsync(() => - new ObsClient(server.Endpoint, null).RequestAsync("StartRecord", new { }, timeout.Token)); - 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) - { - 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 - { - 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 (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); - 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(); } - } -} +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 index cd8f4e3..fdf930f 100644 --- a/tests/ControlHub.Tests/PluginTests.cs +++ b/tests/ControlHub.Tests/PluginTests.cs @@ -1,129 +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("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("androidremote", new("AndroidRemote", "AndroidRemote")); - Assert.Empty(plugin.Descriptor.Actions); - Assert.Equal("not_implemented", (await plugin.GetStatusAsync(default)).State); - Assert.False((await plugin.ExecuteAsync(DispatcherTests.Command("androidremote"), 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 Task ApplyAsync(string action, int? slide, CancellationToken cancellationToken) - { - if (Unavailable) throw new SlideShowUnavailableException(); - Action = action; Slide = slide; return Task.CompletedTask; - } - public Task ReadAsync(CancellationToken cancellationToken) - => Unavailable ? throw new SlideShowUnavailableException() : 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); - } - } -} +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("androidremote", new("AndroidRemote", "AndroidRemote")); + Assert.Empty(plugin.Descriptor.Actions); + Assert.Equal("not_implemented", (await plugin.GetStatusAsync(default)).State); + Assert.False((await plugin.ExecuteAsync(DispatcherTests.Command("androidremote"), 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/streamdeck.test.cjs b/tests/streamdeck.test.cjs index f9d8903..c394064 100644 --- a/tests/streamdeck.test.cjs +++ b/tests/streamdeck.test.cjs @@ -194,3 +194,31 @@ test("overlapping connection checks issue one request", async () => { 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")); + } +}); From 17a7d86b655b7ccbe296dc8918e7dc2226ae734f Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:29:01 +0100 Subject: [PATCH 06/10] =?UTF-8?q?Add=20AndroidRemote=20pairing=20and=20dev?= =?UTF-8?q?ice=20authorization=20/=20Tilf=C3=B8j=20AndroidRemote-parring?= =?UTF-8?q?=20og=20enhedsadgang?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 + ControlHub.slnx | 1 + Plugins/AndroidRemote/AndroidRemotePlugin.cs | 18 + .../ControlHub.Plugins.AndroidRemote.csproj | 5 + Plugins/AndroidRemote/README.md | 14 +- Plugins/AndroidRemote/RemoteCommandGateway.cs | 49 +++ Plugins/AndroidRemote/RemoteDeviceRegistry.cs | 151 ++++++++ Plugins/AndroidRemote/RemotePermissions.cs | 26 ++ README.en.md | 3 +- README.md | 3 +- docs/androidremote.da.md | 48 +++ docs/androidremote.en.md | 48 +++ docs/project.da.md | 8 +- docs/project.en.md | 8 +- docs/protocol.da.md | 14 +- docs/protocol.en.md | 14 +- docs/references.md | 2 + docs/setup.da.md | 4 +- docs/setup.en.md | 4 +- docs/testing.da.md | 14 +- docs/testing.en.md | 14 +- src/ControlHub.Core/CommandDispatcher.cs | 9 +- src/ControlHub.Desktop/HostSession.cs | 20 +- src/ControlHub.Desktop/PackageSelfTest.cs | 17 +- src/ControlHub.Host/ControlHub.Host.csproj | 1 + src/ControlHub.Host/Program.cs | 9 +- tests/ControlHub.Tests/AndroidRemoteTests.cs | 345 ++++++++++++++++++ .../ControlHub.Tests/ControlHub.Tests.csproj | 1 + tests/ControlHub.Tests/PluginTests.cs | 4 +- tests/host-smoke.cjs | 21 +- 30 files changed, 827 insertions(+), 54 deletions(-) create mode 100644 Plugins/AndroidRemote/AndroidRemotePlugin.cs create mode 100644 Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj create mode 100644 Plugins/AndroidRemote/RemoteCommandGateway.cs create mode 100644 Plugins/AndroidRemote/RemoteDeviceRegistry.cs create mode 100644 Plugins/AndroidRemote/RemotePermissions.cs create mode 100644 docs/androidremote.da.md create mode 100644 docs/androidremote.en.md create mode 100644 tests/ControlHub.Tests/AndroidRemoteTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 94c355a..646d409 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ ## 0.0.001 — udviklingsversion / development version ### Dansk +- AndroidRemote-bibliotek med enkeltbrugsparring, enhedsrettigheder, udløb og tilbagekaldelse. Ingen telefonapp eller transport endnu. +- Adgang kontrolleres igen efter kommandokøen; kommandosvar holdes adskilt pr. parret enhed. +- Host-smoketest bruger en separat lokal port, så den åbne Control Hub kan fortsætte. - Konkrete forbindelsesårsager for PowerPoint og OBS i status og Stream Deck, med sikre dansk/engelske tekster. - Afbrudte OBS-kommandoer efter påbegyndt afsendelse rapporteres som ukendt udfald; aldrig automatisk genafsendelse. - Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. @@ -22,6 +25,9 @@ - Fysisk test i det aktive miljø afventer. Ingen release eller tag. ### English +- AndroidRemote library with single-use pairing, device permissions, expiry and revocation. No phone app or transport yet. +- Authorization is rechecked after queueing; command results are isolated per paired device. +- Host smoke tests use a separate local port so the open Control Hub can keep running. - Specific PowerPoint/OBS connection reasons in status and Stream Deck, with safe Danish/English messages. - OBS commands interrupted after transmission starts report an unknown outcome; no automatic retries. - Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. diff --git a/ControlHub.slnx b/ControlHub.slnx index e4ae363..7630f61 100644 --- a/ControlHub.slnx +++ b/ControlHub.slnx @@ -6,6 +6,7 @@ + diff --git a/Plugins/AndroidRemote/AndroidRemotePlugin.cs b/Plugins/AndroidRemote/AndroidRemotePlugin.cs new file mode 100644 index 0000000..24f89eb --- /dev/null +++ b/Plugins/AndroidRemote/AndroidRemotePlugin.cs @@ -0,0 +1,18 @@ +using ControlHub.Contracts; + +namespace ControlHub.Plugins.AndroidRemote; + +// Ærlig kapacitetsstatus: biblioteket er bygget, telefontransporten er ikke. +// Truthful capability status: the library exists, the phone transport does not. +public sealed class AndroidRemotePlugin : IHubPlugin +{ + public PluginDescriptor Descriptor { get; } = new("androidremote", new("AndroidRemote", "AndroidRemote"), "development", []); + private static readonly LocalizedText Message = new( + "Parring og adgangskontrol er forberedt. Telefonforbindelse er endnu ikke implementeret.", + "Pairing and access control are prepared. Phone connectivity is not implemented yet."); + public ValueTask GetStatusAsync(CancellationToken cancellationToken) => ValueTask.FromResult( + new PluginStatus(Descriptor.Id, "unavailable", Message, Wire.Data(new { reason = "transport_not_configured" }))); + public ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) => ValueTask.FromResult( + new CommandResult(HubVersion.Protocol, command.Id, Descriptor.Id, false, "not_implemented", Message)); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj b/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj new file mode 100644 index 0000000..4757ded --- /dev/null +++ b/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj @@ -0,0 +1,5 @@ + + + + + diff --git a/Plugins/AndroidRemote/README.md b/Plugins/AndroidRemote/README.md index 30ce577..3a02b71 100644 --- a/Plugins/AndroidRemote/README.md +++ b/Plugins/AndroidRemote/README.md @@ -1,17 +1,13 @@ -# AndroidRemote / AndroidRemote +# AndroidRemote ## Dansk -Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `androidremote`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. +**Parring og adgangskontrol er implementeret som C#-bibliotek. Telefonapp og transport mangler.** Alt integrationskode ligger under denne mappe. RemoteDeviceRegistry håndterer enkeltbrugsparring, enhedsnøgler, rettigheder, udløb og tilbagekaldelse. RemoteCommandGateway kontrollerer adgang til den fælles dispatcher og status. RemotePermissions accepterer kun kendte PowerPoint- og OBS-handlinger. -Næste prioritet efter Stream Deck/PowerPoint/OBS. Afklar om navnet betyder en eksisterende app eller en ny klient. Design derefter en mobil knapflade, parring, TLS, enhedsgodkendelse, genkaldelse og status. Genbrug protokol v1; åbn ikke den eksisterende loopback-host på LAN. Ingen automatisk replay efter mobil genforbindelse. - -Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. +Hosten registrerer AndroidRemotePlugin med modenhed development, tom handlingsliste og unavailable / transport_not_configured. Ingen nye HTTP-ruter eller netværksporte. Tests bruger simulerede enheder. Læs [design, test og næste trin](../../docs/androidremote.da.md). AndroidRemote er ejerens valgte nye Control Hub-klient til Android; tredjepartskompatibilitet er ikke implementeret. ## English -0.0.001 status: **planned, not implemented**. Plugin ID: `androidremote`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. - -Next priority after Stream Deck/PowerPoint/OBS. Establish whether this means an existing app or a new client. Then design mobile buttons, pairing, TLS, device authorization, revocation and status. Reuse protocol v1; do not expose the existing loopback host on the LAN. Never automatically replay commands after mobile reconnection. +**Pairing and authorization are implemented as a C# library. The phone app and transport remain unimplemented.** All integration code lives in this directory. RemoteDeviceRegistry handles single-use pairing, device credentials, permissions, expiry and revocation. RemoteCommandGateway authorizes access to the shared dispatcher and status. RemotePermissions accepts only known PowerPoint and OBS actions. -Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. +The host registers AndroidRemotePlugin with development maturity, no actions and unavailable / transport_not_configured. No new HTTP routes or listening ports. Tests use simulated devices. Read the [design, tests and next steps](../../docs/androidremote.en.md). AndroidRemote is the owner-selected new Control Hub client for Android; third-party compatibility is not implemented. diff --git a/Plugins/AndroidRemote/RemoteCommandGateway.cs b/Plugins/AndroidRemote/RemoteCommandGateway.cs new file mode 100644 index 0000000..3b12f78 --- /dev/null +++ b/Plugins/AndroidRemote/RemoteCommandGateway.cs @@ -0,0 +1,49 @@ +using System.Security.Cryptography; +using System.Text; +using ControlHub.Contracts; +using ControlHub.Core; + +namespace ControlHub.Plugins.AndroidRemote; + +public sealed record RemoteStatusResult(bool Success, string Code, LocalizedText Message, HubStatus? Status = null); + +// Transportuafhængig adgangskontrol. Kaldes kun bag en fremtidig godkendt TLS-transport. +// Transport-independent access control. Invoke only behind a future approved TLS transport. +public sealed class RemoteCommandGateway(RemoteDeviceRegistry devices, CommandDispatcher dispatcher) +{ + public async Task DispatchAsync(string deviceId, string token, Command command, + CancellationToken cancellationToken = default) + { + var permission = RemotePermissions.ForCommand(command.Plugin, command.Action); + bool Authorized() => devices.Allows(deviceId, token, permission); + if (!Authorized()) return Denied(command); + // Hver parret enhed har sit eget UUID-navnerum; lokale/andre enheders svar kan ikke hentes. + // Each pairing has its own UUID namespace; local/other device results cannot be retrieved. + var forwarded = command; + if (Guid.TryParseExact(command.Id, "D", out var id)) + { + var digest = SHA256.HashData(Encoding.UTF8.GetBytes("androidremote\0" + deviceId + "\0" + id.ToString("D"))); + forwarded = command with { Id = new Guid(digest.AsSpan(0, 16)).ToString("D") }; + } + var result = await dispatcher.DispatchAsync(forwarded, cancellationToken, Authorized); + return result with { Id = command.Id }; + } + + public async Task GetStatusAsync(string deviceId, string token, + CancellationToken cancellationToken = default) + { + bool Authorized() => devices.Allows(deviceId, token, RemotePermissions.Status); + if (!Authorized()) return DeniedStatus(); + var status = await dispatcher.GetStatusAsync(cancellationToken); + // Tilbagekaldelse/udløb under læsning må heller ikke frigive status. + // Revocation/expiry during the read must not release status either. + return Authorized() ? new(true, "ok", new("Status hentet.", "Status retrieved."), status) : DeniedStatus(); + } + + private static CommandResult Denied(Command command) => 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."); + private static RemoteStatusResult DeniedStatus() => new(false, "access_denied", + new("Enheden har ikke adgang til status. Kontrollér parring og rettigheder.", + "This device cannot read status. Check pairing and permissions.")); +} diff --git a/Plugins/AndroidRemote/RemoteDeviceRegistry.cs b/Plugins/AndroidRemote/RemoteDeviceRegistry.cs new file mode 100644 index 0000000..7696f49 --- /dev/null +++ b/Plugins/AndroidRemote/RemoteDeviceRegistry.cs @@ -0,0 +1,151 @@ +using System.Security.Cryptography; +using System.Text; + +namespace ControlHub.Plugins.AndroidRemote; + +public sealed record RemoteDevice(string Id, string Name, IReadOnlyList Permissions, + DateTimeOffset PairedAt, DateTimeOffset ExpiresAt); + +// Almindelige klasser: ToString må ikke udskrive hemmeligheder som en record gør. +// Ordinary classes: ToString must not print secrets as a record would. +public sealed class PairingOffer(string id, string secret, DateTimeOffset expiresAt) +{ + public string Id { get; } = id; + public string Secret { get; } = secret; + public DateTimeOffset ExpiresAt { get; } = expiresAt; +} + +public sealed class DeviceCredential(RemoteDevice device, string token) +{ + public RemoteDevice Device { get; } = device; + public string Token { get; } = token; +} + +// Kun i hukommelsen. Genstart kræver ny parring. Ingen netværkslytter eller filadgang. +// Memory only. Restart requires pairing again. No network listener or file access. +public sealed class RemoteDeviceRegistry(TimeProvider? timeProvider = null) +{ + public static readonly TimeSpan PairingLifetime = TimeSpan.FromMinutes(2); + public static readonly TimeSpan DeviceLifetime = TimeSpan.FromHours(8); + public const int MaximumDevices = 16; + public const int MaximumPendingPairings = 8; + public const int MaximumPairingAttempts = 5; + private readonly TimeProvider clock = timeProvider ?? TimeProvider.System; + private readonly object sync = new(); + private readonly Dictionary pending = new(StringComparer.Ordinal); + private readonly Dictionary devices = new(StringComparer.Ordinal); + + private sealed class Pending(string name, IReadOnlyList permissions, byte[] hash, long created) + { + public string Name { get; } = name; + public IReadOnlyList Permissions { get; } = permissions; + public byte[] Hash { get; } = hash; + public long Created { get; } = created; + public int Attempts { get; set; } + } + private sealed record Paired(RemoteDevice Device, byte[] Hash, long Created); + + // Lokal ejerfunktion; må aldrig eksponeres som en anonym parringstjeneste. + // Local owner operation; never expose this as an anonymous pairing endpoint. + public PairingOffer BeginPairing(string deviceName, IEnumerable permissions) + { + if (string.IsNullOrWhiteSpace(deviceName) || deviceName.Length > 80 || deviceName.Any(char.IsControl)) + throw new ArgumentException("Ugyldigt enhedsnavn / Invalid device name.", nameof(deviceName)); + ArgumentNullException.ThrowIfNull(permissions); + var selected = permissions.Take(RemotePermissions.All.Count + 1).ToArray(); + if (selected.Length == 0 || selected.Length > RemotePermissions.All.Count || + selected.Any(p => !RemotePermissions.All.Contains(p, StringComparer.Ordinal)) || + selected.Distinct(StringComparer.Ordinal).Count() != selected.Length) + throw new ArgumentException("Vælg kendte, entydige rettigheder / Select known, unique permissions.", nameof(permissions)); + var immutable = Array.AsReadOnly(selected.Order(StringComparer.Ordinal).ToArray()); + lock (sync) + { + Prune(); + if (pending.Count >= MaximumPendingPairings || devices.Count + pending.Count >= MaximumDevices) + throw new InvalidOperationException("Enhedsgrænsen er nået / Device limit reached."); + var id = Guid.NewGuid().ToString("D"); + var secret = NewSecret(); + pending.Add(id, new Pending(deviceName.Trim(), immutable, Hash(secret), clock.GetTimestamp())); + return new(id, secret, clock.GetUtcNow() + PairingLifetime); + } + } + + public DeviceCredential? CompletePairing(string? pairingId, string? secret) + { + lock (sync) + { + Prune(); + if (pairingId is null || !pending.TryGetValue(pairingId, out var offer)) return null; + offer.Attempts++; + if (!Matches(offer.Hash, secret)) + { + if (offer.Attempts >= MaximumPairingAttempts) RemovePending(pairingId); + return null; + } + RemovePending(pairingId); // Enkeltbrug, også ved samtidige forsøg / Single use, including concurrent attempts. + var now = clock.GetUtcNow(); + var device = new RemoteDevice(Guid.NewGuid().ToString("D"), offer.Name, offer.Permissions, now, now + DeviceLifetime); + var token = NewSecret(); + devices.Add(device.Id, new(device, Hash(token), clock.GetTimestamp())); + return new(device, token); + } + } + + public bool Allows(string? deviceId, string? token, string? permission) + { + lock (sync) + { + Prune(); + return deviceId is not null && devices.TryGetValue(deviceId, out var entry) && + Matches(entry.Hash, token) && permission is not null && + entry.Device.Permissions.Contains(permission, StringComparer.Ordinal); + } + } + + public IReadOnlyList ListDevices() + { + lock (sync) { Prune(); return devices.Values.Select(d => d.Device).ToArray(); } + } + + public int PendingCount { get { lock (sync) { Prune(); return pending.Count; } } } + public bool CancelPairing(string pairingId) { lock (sync) return RemovePending(pairingId); } + public bool RevokeDevice(string deviceId) { lock (sync) return RemoveDevice(deviceId); } + public void RevokeAll() + { + lock (sync) + { + foreach (var id in pending.Keys.ToArray()) RemovePending(id); + foreach (var id in devices.Keys.ToArray()) RemoveDevice(id); + } + } + + private void Prune() + { + var now = clock.GetTimestamp(); + foreach (var item in pending.Where(p => clock.GetElapsedTime(p.Value.Created, now) >= PairingLifetime).ToArray()) + RemovePending(item.Key); + foreach (var item in devices.Where(p => clock.GetElapsedTime(p.Value.Created, now) >= DeviceLifetime).ToArray()) + RemoveDevice(item.Key); + } + private bool RemovePending(string id) + { + if (!pending.Remove(id, out var entry)) return false; + CryptographicOperations.ZeroMemory(entry.Hash); + return true; + } + private bool RemoveDevice(string id) + { + if (!devices.Remove(id, out var entry)) return false; + CryptographicOperations.ZeroMemory(entry.Hash); + return true; + } + private static string NewSecret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); + private static bool Matches(byte[] expected, string? supplied) + { + if (supplied is null || supplied.Length != 64 || !supplied.All(char.IsAsciiHexDigit)) return false; + var actual = Hash(supplied); + try { return CryptographicOperations.FixedTimeEquals(expected, actual); } + finally { CryptographicOperations.ZeroMemory(actual); } + } +} diff --git a/Plugins/AndroidRemote/RemotePermissions.cs b/Plugins/AndroidRemote/RemotePermissions.cs new file mode 100644 index 0000000..cb2ea80 --- /dev/null +++ b/Plugins/AndroidRemote/RemotePermissions.cs @@ -0,0 +1,26 @@ +namespace ControlHub.Plugins.AndroidRemote; + +// Rettigheder vælges af ejeren, aldrig af telefonens kommando. +// Permissions are selected by the owner, never by a phone's command. +public static class RemotePermissions +{ + public const string Status = "status.read"; + public const string PowerPoint = "powerpoint.control"; + public const string Scenes = "obs.scenes"; + public const string Recording = "obs.recording"; + public const string Streaming = "obs.streaming"; + public const string Audio = "obs.audio"; + + public static IReadOnlyList All { get; } = Array.AsReadOnly(new[] + { Status, PowerPoint, Scenes, Recording, Streaming, Audio }); + + public static string? ForCommand(string plugin, string action) => (plugin, action) switch + { + ("powerpoint", "next" or "previous" or "goto" or "black" or "resume") => PowerPoint, + ("obs", "scene.switch") => Scenes, + ("obs", "record.start" or "record.stop") => Recording, + ("obs", "stream.start" or "stream.stop") => Streaming, + ("obs", "input.mute") => Audio, + _ => null + }; +} diff --git a/README.en.md b/README.en.md index c676166..8882a26 100644 --- a/README.en.md +++ b/README.en.md @@ -14,6 +14,7 @@ The goal is to give operators clear buttons, predictable commands and truthful s - [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) @@ -27,7 +28,7 @@ The goal is to give operators clear buttons, predictable commands and truthful s | 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 | Plugin ID, status placeholder and integration plan | No Android app or pairing yet | +| AndroidRemote | Tested library for pairing, device permissions, expiry, revocation and command authorization | No Android app, pairing dialog or phone transport yet | | 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. diff --git a/README.md b/README.md index 13dee47..5039125 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og - [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) @@ -28,7 +29,7 @@ Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og | 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 | Plugin-id, statuspladsholder og integrationsplan | Ingen Android-app eller parring endnu | +| AndroidRemote | Testet bibliotek til parring, enhedsrettigheder, udløb, tilbagekaldelse og kommandokontrol | Ingen Android-app, parringsdialog eller telefontransport endnu | | 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. diff --git a/docs/androidremote.da.md b/docs/androidremote.da.md new file mode 100644 index 0000000..4c6f158 --- /dev/null +++ b/docs/androidremote.da.md @@ -0,0 +1,48 @@ +# AndroidRemote: parring og adgangskontrol + +[English](androidremote.en.md) + +Første kodetrin er et transportuafhængigt .NET 10-bibliotek under `Plugins/AndroidRemote/`, testet mod den rigtige dispatcher og simulerede enheder. Det er **ikke en installerbar Android-app eller en fungerende telefonforbindelse**. + +## Parringsforløb + +1. En fremtidig lokal ejergrænseflade kalder `BeginPairing` med et navn på 1–80 tegn uden kontroltegn og en eksplicit rettighedsliste. +2. Biblioteket returnerer et parrings-id, et tilfældigt bevis og udløbstidspunkt. Beviset er 32 kryptografisk tilfældige bytes gengivet som 64 hextegn; det er ikke en kort PIN-kode. Det gælder i to minutter. +3. Den fremtidige telefontransport afleverer id og bevis til `CompletePairing`. Højst ét samtidigt forsøg kan lykkes. Fem forkerte forsøg annullerer parringen; ugyldigt formaterede beviser tæller også. +4. Vellykket parring giver et nyt enheds-id og en uafhængig nøgle, som gælder i otte timer. Navn og rettigheder kommer fra ejerens valg; telefonen kan ikke udvide dem. +5. Kommandoer og status går gennem `RemoteCommandGateway`. Forkerte nøgler, manglende rettigheder, tilbagekaldte og udløbne enheder afvises. + +Ejeren kan annullere en parring, tilbagekalde én enhed eller tilbagekalde alle enheder og ventende parringer. Hemmeligheder returneres kun ved oprettelse og må ikke logges. Registeret gemmer SHA-256-hashværdier og sammenligner dem med `CryptographicOperations.FixedTimeEquals`. Enhedslister indeholder ingen nøgler. Dette gælder tilfældige nøgler med stor entropi, ikke brugeradgangskoder. + +Der er højst otte ventende parringer og i alt 16 parrede/reserverede enhedspladser. Udløb bruger monoton tid; ændring af Windows-uret forlænger ikke adgangen. Viste UTC-tidspunkter er vejledende, hvis systemuret ændres. Alt findes kun i hukommelsen. Genstart kræver ny parring. + +## Rettigheder + +| Rettighed | Tillader | +|---|---| +| `status.read` | Hele Control Hub-statusobjektet, inklusive OBS-scenenavn | +| `powerpoint.control` | `next`, `previous`, `goto`, `black`, `resume` | +| `obs.scenes` | `scene.switch` | +| `obs.recording` | `record.start`, `record.stop` | +| `obs.streaming` | `stream.start`, `stream.stop` | +| `obs.audio` | `input.mute` | + +Ingen rettigheder tilføjes automatisk. Der findes ingen wildcard-rettighed. Ukendte og dublerede rettigheder afvises. Rettigheder gælder handlingstyper, ikke individuelle scener/lydkilder. Filredigering, vilkårlige COM-kald og fokusafhængige tastetryk er ikke tilladt. + +## Kø, tilbagekaldelse og dubletter + +Adgang kontrolleres ved modtagelse og efter dispatcherens ventekø, før cachelæsning eller udførelse. Tilbagekaldelse eller udløb under køen afviser dermed stadig ventende kommandoer. Kontrollen efter køen er grænsen for igangsættelse; tilbagekaldelse kan ikke fortryde allerede igangsat arbejde, herunder COM-kald. Status kontrollerer også adgang igen efter indsamling. + +Klientens kommando-UUID mappes deterministisk til et internt UUID i parringens eget navnerum. Svaret får klientens oprindelige id tilbage. Samme id fra to parringer eller fra Stream Deck giver ikke adgang til det samme cachesvar. Historikken er stadig den fælles hukommelsescache med de seneste 1.024 afsendte id'er; den er ikke vedvarende replay-beskyttelse. Ny parring giver et nyt navnerum. Telefonen må aldrig automatisk genafspille gamle kommandoer efter genforbindelse eller genstart. + +`access_denied` har faste danske/engelske tekster og udfører ingen pluginhandling. Timeout efter igangsat adapterarbejde bevarer `outcome_unknown`. Operatøren skal kontrollere status før en ny handling. + +## Før telefonbrug + +Der mangler lokal parringsdialog/enhedsliste, en dansk/engelsk Android-klient og særskilt TLS-transport med verificeret serveridentitet, sikker overførsel af parringsbevis/nøgle og sikker lagring på telefonen. Transporten skal begrænse størrelse, samtidighed og forespørgselshastighed; bibliotekets parringsgrænser erstatter ikke dette. Derefter følger transporttests og fysisk Android-test. + +Der er ingen nye HTTP-endpoints. Parring og tilbagekaldelse er ejerfunktioner i biblioteket, ikke anonyme telefon-API'er. Det lokale Control Hub-token skal ikke kopieres til telefonen. Hosten lytter fortsat kun på loopback; der åbnes ingen firewall eller LAN-adgang. Pluginstatus er `unavailable` / `transport_not_configured` med tom handlingsliste. + +## Test + +Tests dækker samtidig enkeltbrugsparring, udløb, ændring af systemur, forkerte beviser, kapacitetsgrænser, uforanderlige rettigheder, handlingsrettigheder, filhandlingsafvisning, adskilt dublethistorik, tilbagekaldelse/udløb under kø, tilbagekaldelse under statuslæsning, korrelation, timeout og ærlig transportstatus. Ingen præsentation ændres, og ingen virkelig optagelse eller streaming startes. diff --git a/docs/androidremote.en.md b/docs/androidremote.en.md new file mode 100644 index 0000000..8539b4c --- /dev/null +++ b/docs/androidremote.en.md @@ -0,0 +1,48 @@ +# AndroidRemote: pairing and authorization + +[Dansk](androidremote.da.md) + +The first implementation is a transport-independent .NET 10 library under `Plugins/AndroidRemote/`, tested with the real dispatcher and simulated devices. It is **not an installable Android app or a working phone connection**. + +## Pairing flow + +1. A future local owner interface calls `BeginPairing` with a 1–80 character name without control characters and an explicit permission list. +2. The library returns a pairing ID, random secret and expiry time. The secret is 32 cryptographically random bytes represented by 64 hexadecimal characters, not a short PIN. It lasts two minutes. +3. The future phone transport submits the ID and secret to `CompletePairing`. At most one concurrent attempt succeeds. Five incorrect attempts cancel the pairing; malformed secrets count too. +4. Successful pairing issues a new device ID and independent token lasting eight hours. The name and permissions come from the owner's selection; the phone cannot expand them. +5. Commands and status pass through `RemoteCommandGateway`. Incorrect tokens, missing permissions, revoked and expired devices are denied. + +The owner can cancel a pairing, revoke one device or revoke all devices and pending pairings. Secrets are returned only at creation and must never be logged. The registry stores SHA-256 digests and compares them using `CryptographicOperations.FixedTimeEquals`. Device lists contain no credentials. This applies to high-entropy random tokens, not user passwords. + +At most eight pairings may be pending, with a combined limit of 16 paired/reserved device slots. Expiry uses monotonic time; changing the Windows clock does not extend access. Displayed UTC times are advisory if the system clock changes. Everything is memory-only. Restart requires pairing again. + +## Permissions + +| Permission | Allows | +|---|---| +| `status.read` | The complete Control Hub status object, including OBS scene name | +| `powerpoint.control` | `next`, `previous`, `goto`, `black`, `resume` | +| `obs.scenes` | `scene.switch` | +| `obs.recording` | `record.start`, `record.stop` | +| `obs.streaming` | `stream.start`, `stream.stop` | +| `obs.audio` | `input.mute` | + +No permissions are added automatically. There is no wildcard permission. Unknown and duplicate permissions are rejected. Permissions apply to action types, not individual scenes/inputs. File editing, arbitrary COM calls and focus-dependent keystrokes are not allowed. + +## Queueing, revocation and duplicates + +Authorization is checked on receipt and after waiting for the dispatcher, before reading cached results or executing. Revocation or expiry while queued therefore rejects still-pending commands. The post-queue check is the admission boundary; revocation cannot undo already admitted work, including COM calls. Status also rechecks authorization after collection. + +The client's command UUID is deterministically mapped to an internal UUID in the pairing's own namespace. Responses restore the original client ID. An identical ID from two pairings or Stream Deck cannot retrieve the same cached result. History is still the shared in-memory cache of the latest 1,024 dispatched IDs, not persistent replay protection. Pairing again creates a new namespace. Phones must never automatically replay old commands after reconnecting or restarting. + +`access_denied` uses fixed Danish/English messages and executes no plugin action. A timeout after adapter work starts preserves `outcome_unknown`. The operator must check status before another action. + +## Before phone use + +Remaining work includes a local pairing dialog/device list, a Danish/English Android client and separate TLS transport with verified server identity, secure pairing-secret/token transfer and secure storage on the phone. The transport must limit size, concurrency and request rate; library pairing limits do not replace these. Transport tests and physical Android testing must follow. + +There are no new HTTP endpoints. Pairing and revocation are owner operations in the library, not anonymous phone APIs. The local Control Hub token must not be copied to the phone. The host still listens only on loopback; no firewall or LAN access is opened. Plugin status is `unavailable` / `transport_not_configured` with an empty action list. + +## Tests + +Tests cover concurrent single-use pairing, expiry, system-clock changes, incorrect secrets, capacity limits, immutable permissions, action permissions, forbidden file actions, isolated duplicate history, revocation/expiry while queued, revocation during status reads, correlation, timeouts and truthful transport status. No presentation is modified and no real recording or stream is started. diff --git a/docs/project.da.md b/docs/project.da.md index 42a2448..8f7ad20 100644 --- a/docs/project.da.md +++ b/docs/project.da.md @@ -25,7 +25,7 @@ Et enkelt dansk/engelsk Windows-kontrolvindue og en brugerinstallation er inklud ```mermaid flowchart LR SD["Stream Deck-plugin"] -->|"HTTP på loopback + token"| H["Control Hub Host"] - AR["AndroidRemote · planlagt"] -.->|"Fremtidig parret transport"| H + AR["AndroidRemote · parring/adgang i bibliotek"] -.->|"Fremtidig parret transport"| H H --> C["Validering og dispatcher"] C --> P["PowerPoint-plugin · STA / COM"] C --> O["OBS-plugin · WebSocket v5"] @@ -78,7 +78,7 @@ Første version opretter en forbindelse pr. forespørgsel. Det forenkler genopre 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 @@ -96,3 +96,7 @@ Automatiske tests dækker routing, validering, dubletter, timeout, adaptergræns 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. Telefonapp, ejerens parringsdialog og TLS-transport mangler fortsat. Hosten viser dette som utilgængelig transport og åbner ingen fjernadgang. Se [design og afgrænsning](androidremote.da.md). diff --git a/docs/project.en.md b/docs/project.en.md index b78bf6f..d1b8306 100644 --- a/docs/project.en.md +++ b/docs/project.en.md @@ -25,7 +25,7 @@ A small Danish/English Windows control window and per-user installer are include ```mermaid flowchart LR SD["Stream Deck plugin"] -->|"Loopback HTTP + token"| H["Control Hub Host"] - AR["AndroidRemote · planned"] -.->|"Future paired transport"| H + AR["AndroidRemote · pairing/access library"] -.->|"Future paired transport"| H H --> C["Validation and dispatcher"] C --> P["PowerPoint plugin · STA / COM"] C --> O["OBS plugin · WebSocket v5"] @@ -78,7 +78,7 @@ The first version opens one connection per request. This simplifies recovery aft 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 @@ -96,3 +96,7 @@ Automated tests cover routing, validation, duplicates, timeouts, adapter boundar 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 phone app, owner pairing dialog and TLS transport remain unimplemented. The host reports unavailable transport and opens no remote access. See the [design and scope](androidremote.en.md). diff --git a/docs/protocol.da.md b/docs/protocol.da.md index ae112d6..6e04576 100644 --- a/docs/protocol.da.md +++ b/docs/protocol.da.md @@ -76,14 +76,18 @@ Status indeholder `protocolVersion`, `version`, `observedAt` og `plugins`. Hvert - 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 annoncerer nu modenhed `development`, tom handlingsliste og `unavailable` med `data.reason = transport_not_configured`. Biblioteket har ingen HTTP-ruter endnu. 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). diff --git a/docs/protocol.en.md b/docs/protocol.en.md index 1ac7331..1dd8223 100644 --- a/docs/protocol.en.md +++ b/docs/protocol.en.md @@ -76,14 +76,18 @@ Status contains `protocolVersion`, `version`, `observedAt` and `plugins`. Each p - 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 now advertises `development` maturity, no actions and `unavailable` with `data.reason = transport_not_configured`. The library has no HTTP routes yet. 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). diff --git a/docs/references.md b/docs/references.md index ffeafd0..1672fe5 100644 --- a/docs/references.md +++ b/docs/references.md @@ -15,3 +15,5 @@ Disse officielle kilder ligger til grund for integrationsvalgene. / These offici - [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 index ed5837d..d9c636a 100644 --- a/docs/setup.da.md +++ b/docs/setup.da.md @@ -25,7 +25,7 @@ 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å port 5187. Stop din normale host først. Den bruger et tilfældigt testtoken, kontakter ikke produktions-OBS og sender ingen slideshow-kommandoer, men læser PowerPoint-status. +`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 @@ -91,3 +91,5 @@ Status opdateres cirka hvert tredje sekund, når forbindelserne svarer hurtigt. ## 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 index d450235..010d874 100644 --- a/docs/setup.en.md +++ b/docs/setup.en.md @@ -25,7 +25,7 @@ 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 port 5187. Stop your normal host first. It uses a random test token, does not contact production OBS and sends no slideshow commands, but reads PowerPoint status. +`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 @@ -91,3 +91,5 @@ Status normally refreshes approximately every three seconds when connections res ## 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 index 1ad7a8b..5ceb3bc 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -49,13 +49,17 @@ Beregn filhash med `Get-FileHash -Algorithm SHA256 -LiteralPath ''` before and a 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. diff --git a/src/ControlHub.Core/CommandDispatcher.cs b/src/ControlHub.Core/CommandDispatcher.cs index 0979cdf..9efe888 100644 --- a/src/ControlHub.Core/CommandDispatcher.cs +++ b/src/ControlHub.Core/CommandDispatcher.cs @@ -20,7 +20,8 @@ public CommandDispatcher(IEnumerable plugins, TimeSpan? timeout = nu this.timeout = timeout ?? TimeSpan.FromSeconds(10); } - public async Task DispatchAsync(Command command, CancellationToken cancellationToken = default) + 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."); @@ -41,6 +42,12 @@ public async Task DispatchAsync(Command command, CancellationToke } 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)) diff --git a/src/ControlHub.Desktop/HostSession.cs b/src/ControlHub.Desktop/HostSession.cs index 0e65d6b..b5d332e 100644 --- a/src/ControlHub.Desktop/HostSession.cs +++ b/src/ControlHub.Desktop/HostSession.cs @@ -11,8 +11,19 @@ internal sealed class HostSession : IDisposable { private Process? process; private readonly HttpClient client = new() { Timeout = TimeSpan.FromSeconds(35) }; + private readonly int portNumber; + 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) + { + if (portNumber is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(portNumber)); + this.portNumber = portNumber; + apiBase = $"http://127.0.0.1:{portNumber}/api/v1/"; + } + public async Task StartAsync(Settings settings) { settings.Validate(); @@ -21,8 +32,8 @@ public async Task StartAsync(Settings settings) { try { - await port.ConnectAsync(IPAddress.Loopback, 5187); - throw new InvalidOperationException("Port 5187 er optaget. Stop den anden host først. / Port 5187 is in use. Stop the other host first."); + 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) { } } @@ -34,6 +45,7 @@ public async Task StartAsync(Settings settings) RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true }; start.Environment["CONTROLHUB_TOKEN"] = settings.Token; + start.Environment["CONTROLHUB_PORT"] = portNumber.ToString(System.Globalization.CultureInfo.InvariantCulture); start.Environment["CONTROLHUB_OBS_URL"] = settings.ObsUrl; start.Environment["CONTROLHUB_OBS_PASSWORD"] = settings.ObsPassword; start.Environment["CONTROLHUB_DESKTOP_LIFETIME"] = "stdin"; @@ -51,7 +63,7 @@ public async Task StartAsync(Settings settings) if (process.HasExited) throw new InvalidOperationException("Hosten stoppede under start / Host exited during startup"); try { - using var response = await client.GetAsync("http://127.0.0.1:5187/api/v1/plugins"); + using var response = await client.GetAsync(apiBase + "plugins"); if (response.IsSuccessStatusCode) return; } catch (HttpRequestException) { } @@ -65,7 +77,7 @@ public async Task StartAsync(Settings settings) public async Task StatusAsync() { if (!IsRunning) throw new InvalidOperationException("Control Hub er stoppet / Control Hub is stopped"); - using var response = await client.GetAsync("http://127.0.0.1:5187/api/v1/status"); + using var response = await client.GetAsync(apiBase + "status"); response.EnsureSuccessStatusCode(); return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); } diff --git a/src/ControlHub.Desktop/PackageSelfTest.cs b/src/ControlHub.Desktop/PackageSelfTest.cs index b329c53..47ed389 100644 --- a/src/ControlHub.Desktop/PackageSelfTest.cs +++ b/src/ControlHub.Desktop/PackageSelfTest.cs @@ -1,6 +1,8 @@ using System.Security.Cryptography; using System.Text; using System.Text.Json; +using System.Net; +using System.Net.Sockets; namespace ControlHub.Desktop; @@ -34,7 +36,13 @@ public static async Task RunAsync(string outputDirectory) try { store.Load(); throw new InvalidDataException("Corrupt settings accepted"); } catch (CryptographicException) { checks.Add("Corrupt encrypted settings rejected"); } store.Save(original); - using var host = new HostSession(); + 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); await host.StartAsync(original); try { @@ -42,8 +50,13 @@ public static async Task RunAsync(string outputDirectory) 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() != "unavailable" || + remote.GetProperty("data").GetProperty("reason").GetString() != "transport_not_configured") + throw new InvalidDataException("AndroidRemote capability status failed"); + checks.Add("AndroidRemote library reports unavailable phone transport"); checks.Add("Published host starts; authenticated status works; test OBS is isolated"); - using var other = new HostSession(); + 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(); diff --git a/src/ControlHub.Host/ControlHub.Host.csproj b/src/ControlHub.Host/ControlHub.Host.csproj index a2f8be6..aa35259 100644 --- a/src/ControlHub.Host/ControlHub.Host.csproj +++ b/src/ControlHub.Host/ControlHub.Host.csproj @@ -1,5 +1,6 @@ + diff --git a/src/ControlHub.Host/Program.cs b/src/ControlHub.Host/Program.cs index d7c6af9..bd8ce34 100644 --- a/src/ControlHub.Host/Program.cs +++ b/src/ControlHub.Host/Program.cs @@ -5,6 +5,7 @@ using System.Threading.RateLimiting; using ControlHub.Contracts; using ControlHub.Core; +using ControlHub.Plugins.AndroidRemote; using ControlHub.Plugins.Obs; using ControlHub.Plugins.Planned; using ControlHub.Plugins.PowerPoint; @@ -14,10 +15,14 @@ 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, 5187); + options.Listen(IPAddress.Loopback, port); options.Limits.MaxRequestBodySize = 16 * 1024; }); builder.Services.AddRateLimiter(options => @@ -35,7 +40,7 @@ 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 PlannedPlugin("androidremote", new("AndroidRemote", "AndroidRemote")), + new AndroidRemotePlugin(), new PlannedPlugin("audio", new("Lyd", "Audio")), new PlannedPlugin("logitech", new("Logitech", "Logitech")), new PlannedPlugin("android-live", new("Android Live", "Android Live")), 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 index f842a6b..d07dd65 100644 --- a/tests/ControlHub.Tests/ControlHub.Tests.csproj +++ b/tests/ControlHub.Tests/ControlHub.Tests.csproj @@ -1,6 +1,7 @@ falsetrue + all diff --git a/tests/ControlHub.Tests/PluginTests.cs b/tests/ControlHub.Tests/PluginTests.cs index fdf930f..27e4682 100644 --- a/tests/ControlHub.Tests/PluginTests.cs +++ b/tests/ControlHub.Tests/PluginTests.cs @@ -105,10 +105,10 @@ public async Task ObsSceneAndMuteValidateAndMapArguments() [Fact] public async Task PlannedIntegrationCannotPretendToExecute() { - await using var plugin = new PlannedPlugin("androidremote", new("AndroidRemote", "AndroidRemote")); + 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("androidremote"), default)).Success); + Assert.False((await plugin.ExecuteAsync(DispatcherTests.Command("audio"), default)).Success); } [Theory] diff --git a/tests/host-smoke.cjs b/tests/host-smoke.cjs index cb41e02..95e9e3f 100644 --- a/tests/host-smoke.cjs +++ b/tests/host-smoke.cjs @@ -3,18 +3,22 @@ const { spawn } = require("node:child_process"); const { randomBytes, randomUUID } = require("node:crypto"); const token = randomBytes(32).toString("hex"); const child = spawn("dotnet", ["src/ControlHub.Host/bin/Release/net10.0/ControlHub.Host.dll"], - { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); + { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_PORT: "0", CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); let log = ""; -child.stdout.on("data", d => { log = (log + d).slice(-4000); }); +let base; +child.stdout.on("data", d => { + 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 base = "http://127.0.0.1:5187/api/v1/"; 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((await fetch(base+"plugins")).status===401) {ready=true;break;} } catch {} + 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)); } @@ -34,11 +38,16 @@ const post = body => fetch(base + "commands", {method:"POST",headers,body:JSON.s 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,"not_implemented"); + 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)); + 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, From 0f6f81f1086825833b43dffc34345a4e4a7f59b9 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:54:50 +0100 Subject: [PATCH 07/10] =?UTF-8?q?Administr=C3=A9r=20telefonadgang=20fra=20?= =?UTF-8?q?Windows=20/=20Manage=20AndroidRemote=20invitations=20from=20Win?= =?UTF-8?q?dows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 + ControlHub.slnx | 2 + Plugins/AndroidRemote/AndroidRemotePlugin.cs | 4 +- .../ControlHub.Plugins.AndroidRemote.csproj | 1 + ...olHub.Plugins.AndroidRemote.Desktop.csproj | 10 + .../Desktop/PhoneAccessWindow.cs | 204 ++++++++++++++++++ ...ntrolHub.Plugins.AndroidRemote.Host.csproj | 6 + Plugins/AndroidRemote/Host/OwnerEndpoints.cs | 67 ++++++ Plugins/AndroidRemote/OwnerProtocol.cs | 79 +++++++ Plugins/AndroidRemote/README.md | 4 +- Plugins/AndroidRemote/RemoteDeviceRegistry.cs | 17 +- README.en.md | 2 +- README.md | 2 +- docs/androidremote.da.md | 6 +- docs/androidremote.en.md | 6 +- docs/installation.da.html | 3 +- docs/installation.en.html | 3 +- docs/project.da.md | 2 +- docs/project.en.md | 2 +- docs/protocol.da.md | 16 +- docs/protocol.en.md | 16 +- docs/testing.da.md | 6 +- docs/testing.en.md | 6 +- .../ControlHub.Desktop.csproj | 3 + src/ControlHub.Desktop/HostSession.cs | 11 +- src/ControlHub.Desktop/MainWindow.cs | 13 +- src/ControlHub.Desktop/PackageSelfTest.cs | 9 + src/ControlHub.Host/ControlHub.Host.csproj | 1 + src/ControlHub.Host/Program.cs | 4 + tests/ControlHub.Tests/RemoteOwnerTests.cs | 62 ++++++ tests/host-smoke.cjs | 4 +- tests/remote-owner-smoke.cjs | 42 ++++ 32 files changed, 589 insertions(+), 26 deletions(-) create mode 100644 Plugins/AndroidRemote/Desktop/ControlHub.Plugins.AndroidRemote.Desktop.csproj create mode 100644 Plugins/AndroidRemote/Desktop/PhoneAccessWindow.cs create mode 100644 Plugins/AndroidRemote/Host/ControlHub.Plugins.AndroidRemote.Host.csproj create mode 100644 Plugins/AndroidRemote/Host/OwnerEndpoints.cs create mode 100644 Plugins/AndroidRemote/OwnerProtocol.cs create mode 100644 tests/ControlHub.Tests/RemoteOwnerTests.cs create mode 100644 tests/remote-owner-smoke.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 646d409..71acdce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.0.001 — udviklingsversion / development version ### Dansk +- Nyt Windows-vindue **Administrér telefonadgang**: vælg rettigheder, opret et to-minutters bevis, se ventende/parrede enheder og tilbagekald adgang. Lokale ejerruter kræver en separat nøgle for hver opstart; Stream Deck-nøglen alene er utilstrækkelig. Android-app og telefontransport mangler stadig. - AndroidRemote-bibliotek med enkeltbrugsparring, enhedsrettigheder, udløb og tilbagekaldelse. Ingen telefonapp eller transport endnu. - Adgang kontrolleres igen efter kommandokøen; kommandosvar holdes adskilt pr. parret enhed. - Host-smoketest bruger en separat lokal port, så den åbne Control Hub kan fortsætte. @@ -25,6 +26,7 @@ - Fysisk test i det aktive miljø afventer. Ingen release eller tag. ### English +- New Windows **Manage phone access** dialog: select permissions, create a two-minute invitation, list pending/paired devices and revoke access. Local owner routes require a separate key for each launch; the Stream Deck key alone is insufficient. Android app and phone transport remain unimplemented. - AndroidRemote library with single-use pairing, device permissions, expiry and revocation. No phone app or transport yet. - Authorization is rechecked after queueing; command results are isolated per paired device. - Host smoke tests use a separate local port so the open Control Hub can keep running. diff --git a/ControlHub.slnx b/ControlHub.slnx index 7630f61..ea2b8e7 100644 --- a/ControlHub.slnx +++ b/ControlHub.slnx @@ -7,6 +7,8 @@ + + diff --git a/Plugins/AndroidRemote/AndroidRemotePlugin.cs b/Plugins/AndroidRemote/AndroidRemotePlugin.cs index 24f89eb..3e332fa 100644 --- a/Plugins/AndroidRemote/AndroidRemotePlugin.cs +++ b/Plugins/AndroidRemote/AndroidRemotePlugin.cs @@ -8,8 +8,8 @@ public sealed class AndroidRemotePlugin : IHubPlugin { public PluginDescriptor Descriptor { get; } = new("androidremote", new("AndroidRemote", "AndroidRemote"), "development", []); private static readonly LocalizedText Message = new( - "Parring og adgangskontrol er forberedt. Telefonforbindelse er endnu ikke implementeret.", - "Pairing and access control are prepared. Phone connectivity is not implemented yet."); + "Telefonadgang kan administreres i Control Hub. Telefonforbindelsen er endnu ikke klar.", + "Phone access can be managed in Control Hub. Phone connectivity is not available yet."); public ValueTask GetStatusAsync(CancellationToken cancellationToken) => ValueTask.FromResult( new PluginStatus(Descriptor.Id, "unavailable", Message, Wire.Data(new { reason = "transport_not_configured" }))); public ValueTask ExecuteAsync(Command command, CancellationToken cancellationToken) => ValueTask.FromResult( diff --git a/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj b/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj index 4757ded..5cf8aa4 100644 --- a/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj +++ b/Plugins/AndroidRemote/ControlHub.Plugins.AndroidRemote.csproj @@ -1,5 +1,6 @@ + diff --git a/Plugins/AndroidRemote/Desktop/ControlHub.Plugins.AndroidRemote.Desktop.csproj b/Plugins/AndroidRemote/Desktop/ControlHub.Plugins.AndroidRemote.Desktop.csproj new file mode 100644 index 0000000..3b7cf81 --- /dev/null +++ b/Plugins/AndroidRemote/Desktop/ControlHub.Plugins.AndroidRemote.Desktop.csproj @@ -0,0 +1,10 @@ + + + net10.0-windows + true + true + + + + + diff --git a/Plugins/AndroidRemote/Desktop/PhoneAccessWindow.cs b/Plugins/AndroidRemote/Desktop/PhoneAccessWindow.cs new file mode 100644 index 0000000..4451fb7 --- /dev/null +++ b/Plugins/AndroidRemote/Desktop/PhoneAccessWindow.cs @@ -0,0 +1,204 @@ +using System.Net; +using System.Text.Json; +using ControlHub.Contracts; + +namespace ControlHub.Plugins.AndroidRemote.Desktop; + +public sealed class PhoneAccessWindow : Form +{ + private readonly IRemoteOwnerClient owner; + private readonly bool danish; + private readonly TextBox name = new() { Width = 400, MaxLength = 80 }; + private readonly CheckedListBox permissions = new() { Width = 400, Height = 138, CheckOnClick = true }; + private readonly ListView list = new() { Width = 650, Height = 155, View = View.Details, + FullRowSelect = true, MultiSelect = false, HideSelection = false }; + private readonly Label feedback = new() { AutoSize = true, MaximumSize = new Size(650, 0) }; + private readonly Button create = new() { AutoSize = true }, copy = new() { AutoSize = true }, + remove = new() { AutoSize = true }, all = new() { AutoSize = true }, refresh = new() { AutoSize = true }; + private readonly System.Windows.Forms.Timer timer = new() { Interval = 4000 }; + private readonly CancellationTokenSource lifetime = new(); + private PairingOffer? offer; + private bool busy, loaded, closed; + private sealed record Row(string Id, bool Pending, string Name); + private string T(string da, string en) => danish ? da : en; + private string PermissionLabel(string id) => id switch + { + RemotePermissions.Status => T("Læs status", "Read status"), + RemotePermissions.PowerPoint => T("Styr slides", "Control slides"), + RemotePermissions.Scenes => T("Skift OBS-scene", "Switch OBS scene"), + RemotePermissions.Recording => T("Start og stop optagelse", "Start and stop recording"), + RemotePermissions.Streaming => T("Start og stop streaming", "Start and stop streaming"), + RemotePermissions.Audio => T("Slå OBS-lyd til og fra", "Mute and unmute OBS audio"), + _ => T("Ukendt rettighed", "Unknown permission") + }; + + public PhoneAccessWindow(IRemoteOwnerClient owner, bool danish) + { + this.owner = owner; + this.danish = danish; + Text = T("AndroidRemote · Telefonadgang", "AndroidRemote · Phone access"); + AutoScaleMode = AutoScaleMode.Dpi; + Font = new Font("Segoe UI", 10); + ClientSize = new Size(720, 690); + MinimumSize = new Size(550, 490); + StartPosition = FormStartPosition.CenterParent; + var flow = new FlowLayoutPanel { Dock = DockStyle.Fill, AutoScroll = true, WrapContents = false, + FlowDirection = FlowDirection.TopDown, Padding = new Padding(18) }; + Controls.Add(flow); + var heading = LabelFor(T("Telefonadgang", "Phone access")); + heading.Font = new Font(Font, FontStyle.Bold); + flow.Controls.AddRange([heading, LabelFor(T( + "Du kan oprette og fjerne parringsbeviser her. Android-appen og telefonforbindelsen er endnu ikke klar.", + "You can create and remove pairing invitations here. The Android app and phone connection are not available yet.")), + LabelFor(T("Telefonens navn", "Phone name")), name, + LabelFor(T("Hvad må telefonen gøre?", "What may this phone do?")), permissions]); + name.AccessibleName = T("Telefonens navn", "Phone name"); + permissions.AccessibleName = T("Telefonens rettigheder", "Phone permissions"); + foreach (var id in RemotePermissions.All) permissions.Items.Add(PermissionLabel(id), false); + create.Text = T("Opret parringsbevis", "Create invitation"); + copy.Text = T("Kopiér nyt bevis", "Copy new invitation"); + remove.Text = T("Fjern valgt adgang", "Remove selected access"); + all.Text = T("Fjern al adgang", "Remove all access"); + refresh.Text = T("Opdater listen", "Refresh list"); + flow.Controls.Add(Buttons(create, copy)); + flow.Controls.Add(LabelFor(T("Parringsbeviser og parrede telefoner", "Invitations and paired phones"))); + list.AccessibleName = T("Telefonadgang", "Phone access"); + list.Columns.Add(T("Navn", "Name"), 165); + list.Columns.Add(T("Type", "Type"), 110); + list.Columns.Add(T("Rettigheder", "Permissions"), 250); + list.Columns.Add(T("Udløber", "Expires"), 90); + flow.Controls.Add(list); + flow.Controls.Add(Buttons(refresh, remove, all)); + flow.Controls.Add(feedback); + var close = new Button { AutoSize = true, Text = T("Luk", "Close") }; + close.Click += (_, _) => Close(); + flow.Controls.Add(close); + CancelButton = close; + + name.TextChanged += (_, _) => UpdateEnabled(); + permissions.ItemCheck += (_, _) => { if (IsHandleCreated) BeginInvoke(UpdateEnabled); }; + list.SelectedIndexChanged += (_, _) => UpdateEnabled(); + create.Click += async (_, _) => await RunAsync(async ct => + { + var selected = permissions.CheckedIndices.Cast().Select(i => RemotePermissions.All[i]).ToArray(); + offer = null; + var created = await owner.BeginAsync(name.Text.Trim(), selected, ct); + if (closed) return; + offer = created; + await ReloadAsync(ct); + if (!closed) feedback.Text = T("Beviset gælder i to minutter. Listen viser ikke den hemmelige nøgle.", + "The invitation lasts two minutes. The list does not show its secret."); + }); + copy.Click += async (_, _) => await RunAsync(async ct => + { + await ReloadAsync(ct); + if (closed) return; + if (offer is null) { feedback.Text = T("Beviset er ikke længere aktivt.", "The invitation is no longer active."); return; } + Clipboard.SetText(JsonSerializer.Serialize(offer, Wire.Json)); + feedback.Text = T("Parringsbevis kopieret. Del det kun med den tiltænkte telefon.", + "Invitation copied. Share it only with the intended phone."); + }); + remove.Click += async (_, _) => + { + if (Selection() is not Row row) return; + if (!Confirm(T($"Fjern adgangen for »{row.Name}«?", $"Remove access for “{row.Name}”?"))) return; + await RunAsync(async ct => { await owner.RemoveAsync(row.Id, row.Pending, ct); await ReloadAsync(ct); + if (!closed) feedback.Text = T("Adgangen er fjernet.", "Access removed."); }); + }; + all.Click += async (_, _) => + { + if (!Confirm(T("Fjern alle telefoner og ventende parringsbeviser?", "Remove all phones and pending invitations?"))) return; + await RunAsync(async ct => { await owner.RevokeAllAsync(ct); await ReloadAsync(ct); + if (!closed) feedback.Text = T("Al telefonadgang er fjernet.", "All phone access removed."); }); + }; + refresh.Click += async (_, _) => await RunAsync(ReloadAsync); + Shown += async (_, _) => { await RunAsync(ReloadAsync); if (!closed) timer.Start(); }; + timer.Tick += async (_, _) => await RunAsync(ReloadAsync); + UpdateEnabled(); + } + + private Row? Selection() => list.SelectedItems.Count == 1 ? list.SelectedItems[0].Tag as Row : null; + private static Label LabelFor(string value) => new() { Text = value, AutoSize = true, MaximumSize = new Size(650, 0), + Margin = new Padding(3, 8, 3, 3) }; + private static FlowLayoutPanel Buttons(params Button[] buttons) + { + var panel = new FlowLayoutPanel { AutoSize = true, WrapContents = true }; + panel.Controls.AddRange(buttons); + return panel; + } + private bool Confirm(string text) => MessageBox.Show(this, text, Text, MessageBoxButtons.YesNo, + MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes; + + private async Task ReloadAsync(CancellationToken ct) + { + var snapshot = await owner.GetAsync(ct); + if (closed) return; + var selected = Selection(); + list.BeginUpdate(); + try + { + list.Items.Clear(); + foreach (var p in snapshot.PendingPairings) AddRow(new(p.Id, true, p.Name), p.Permissions, p.ExpiresAt, selected); + foreach (var d in snapshot.Devices) AddRow(new(d.Id, false, d.Name), d.Permissions, d.ExpiresAt, selected); + } + finally { list.EndUpdate(); } + if (offer is not null && !snapshot.PendingPairings.Any(p => p.Id == offer.Id)) + { + offer = null; + feedback.Text = T("Det seneste bevis er ikke længere aktivt.", "The latest invitation is no longer active."); + } + if (!loaded) feedback.Text = list.Items.Count == 0 ? T("Ingen telefoner eller ventende beviser.", "No phones or pending invitations.") + : T("Listen er opdateret.", "List refreshed."); + loaded = true; + } + + private void AddRow(Row row, IReadOnlyList scopes, DateTimeOffset expires, Row? selected) + { + var item = new ListViewItem(new[] { row.Name, row.Pending ? T("Venter", "Pending") : T("Parret", "Paired"), + string.Join(", ", scopes.Select(PermissionLabel)), expires.ToLocalTime().ToString("T") }) { Tag = row }; + list.Items.Add(item); + item.Selected = selected == row; + } + + private async Task RunAsync(Func action) + { + if (busy || closed) return; + busy = true; + UpdateEnabled(); + try { await action(lifetime.Token); } + catch (Exception) when (closed) { } + catch (HttpRequestException e) when (!closed && e.StatusCode == HttpStatusCode.Conflict) + { + feedback.Text = T("Der er ikke plads til flere beviser. Fjern et gammelt bevis først.", + "Invitation limit reached. Remove an older invitation first."); + } + catch (Exception) when (!closed) + { + loaded = false; + feedback.Text = T("Handlingen kunne ikke bekræftes. Opdater listen, før du prøver igen.", + "The operation could not be confirmed. Refresh the list before trying again."); + } + finally { busy = false; if (!closed) UpdateEnabled(); } + } + private void UpdateEnabled() + { + if (closed) return; + create.Enabled = !busy && loaded && !string.IsNullOrWhiteSpace(name.Text) && permissions.CheckedItems.Count > 0; + copy.Enabled = !busy && loaded && offer is not null; + remove.Enabled = !busy && loaded && Selection() is not null; + all.Enabled = !busy && loaded && list.Items.Count != 0; + refresh.Enabled = !busy; + } + protected override void Dispose(bool disposing) + { + if (disposing && !closed) + { + closed = true; + timer.Dispose(); + lifetime.Cancel(); + lifetime.Dispose(); + offer = null; + } + base.Dispose(disposing); + } +} diff --git a/Plugins/AndroidRemote/Host/ControlHub.Plugins.AndroidRemote.Host.csproj b/Plugins/AndroidRemote/Host/ControlHub.Plugins.AndroidRemote.Host.csproj new file mode 100644 index 0000000..67d71b4 --- /dev/null +++ b/Plugins/AndroidRemote/Host/ControlHub.Plugins.AndroidRemote.Host.csproj @@ -0,0 +1,6 @@ + + + + + + diff --git a/Plugins/AndroidRemote/Host/OwnerEndpoints.cs b/Plugins/AndroidRemote/Host/OwnerEndpoints.cs new file mode 100644 index 0000000..dc10e44 --- /dev/null +++ b/Plugins/AndroidRemote/Host/OwnerEndpoints.cs @@ -0,0 +1,67 @@ +using System.Text.Json; +using System.Security.Cryptography; +using System.Net; +using System.Text; +using ControlHub.Contracts; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; + +namespace ControlHub.Plugins.AndroidRemote.Host; + +public static class OwnerEndpoints +{ + // Skal placeres bag hostens ejer-godkendelse, Origin-afvisning og størrelsesgrænse. + // Must sit behind host owner authentication, Origin rejection and body-size limits. + public static void MapAndroidRemoteOwner(this IEndpointRouteBuilder routes, RemoteDeviceRegistry devices, string ownerKey) + { + var expected = SHA256.HashData(Encoding.UTF8.GetBytes(ownerKey)); + var group = routes.MapGroup("/api/v1/androidremote/owner").RequireRateLimiting("local"); + group.AddEndpointFilter(async (context, next) => + { + context.HttpContext.Response.Headers.CacheControl = "no-store"; + context.HttpContext.Response.Headers.Pragma = "no-cache"; + if (context.HttpContext.Connection.RemoteIpAddress is not { } peer || !IPAddress.IsLoopback(peer)) + return Results.StatusCode(StatusCodes.Status403Forbidden); + var proof = context.HttpContext.Request.Headers["X-ControlHub-Owner"]; + if (proof.Count != 1 || !CryptographicOperations.FixedTimeEquals(expected, + SHA256.HashData(Encoding.UTF8.GetBytes(proof.ToString())))) + return Results.StatusCode(StatusCodes.Status403Forbidden); + return await next(context); + }); + group.MapGet("/", () => Results.Json(devices.GetOwnerSnapshot(), Wire.Json)); + group.MapPost("/pairings", async (HttpRequest request, CancellationToken ct) => + { + try + { + using var document = await JsonDocument.ParseAsync(request.Body, new JsonDocumentOptions { MaxDepth = 16 }, ct); + var root = document.RootElement; + if (!Wire.OnlyArguments(root, "name", "permissions") || + !root.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String || + !root.TryGetProperty("permissions", out var permissions) || permissions.ValueKind != JsonValueKind.Array || + permissions.GetArrayLength() > RemotePermissions.All.Count || + permissions.EnumerateArray().Any(p => p.ValueKind != JsonValueKind.String)) return Invalid(); + var offer = devices.BeginPairing(name.GetString()!, permissions.EnumerateArray().Select(p => p.GetString()!)); + return Results.Json(offer, Wire.Json, statusCode: StatusCodes.Status201Created); + } + catch (JsonException) { return Invalid(); } + catch (ArgumentException) { return Invalid(); } + catch (InvalidOperationException) + { + return Results.Json(new { code = "capacity_reached", message = new LocalizedText( + "Fjern en gammel parring eller enhed først.", "Remove an old pairing or device first.") }, Wire.Json, statusCode: 409); + } + }); + group.MapDelete("/pairings/{id}", (string id) => Remove(id, devices.CancelPairing)); + group.MapDelete("/devices/{id}", (string id) => Remove(id, devices.RevokeDevice)); + group.MapDelete("/access", () => { devices.RevokeAll(); return Results.NoContent(); }); + } + + private static IResult Remove(string id, Func remove) + { + if (!Guid.TryParseExact(id, "D", out var guid)) return Invalid(); + return remove(guid.ToString("D")) ? Results.NoContent() : Results.NotFound(); + } + private static IResult Invalid() => Results.BadRequest(new { code = "invalid_pairing", message = new LocalizedText( + "Vælg et gyldigt navn og mindst én kendt rettighed.", "Choose a valid name and at least one known permission.") }); +} diff --git a/Plugins/AndroidRemote/OwnerProtocol.cs b/Plugins/AndroidRemote/OwnerProtocol.cs new file mode 100644 index 0000000..275a701 --- /dev/null +++ b/Plugins/AndroidRemote/OwnerProtocol.cs @@ -0,0 +1,79 @@ +using System.Net; +using System.Net.Http.Json; +using ControlHub.Contracts; + +namespace ControlHub.Plugins.AndroidRemote; + +public sealed record PendingPairing(string Id, string Name, IReadOnlyList Permissions, DateTimeOffset ExpiresAt); +public sealed record RemoteOwnerSnapshot(bool TransportReady, IReadOnlyList Devices, + IReadOnlyList PendingPairings); +public sealed record BeginPairingRequest(string Name, IReadOnlyList Permissions); + +public interface IRemoteOwnerClient +{ + Task GetAsync(CancellationToken cancellationToken = default); + Task BeginAsync(string name, IReadOnlyList permissions, CancellationToken cancellationToken = default); + Task RemoveAsync(string id, bool pending, CancellationToken cancellationToken = default); + Task RevokeAllAsync(CancellationToken cancellationToken = default); +} + +// Kun ejerens lokale API. Klienten ejer ikke HttpClient eller dens forbindelsesnøgle. +// Local owner API only. This client does not own HttpClient or its connection key. +public sealed class RemoteOwnerClient : IRemoteOwnerClient +{ + private readonly HttpClient client; + private readonly Uri endpoint; + private readonly string ownerKey; + public RemoteOwnerClient(HttpClient client, Uri endpoint, string ownerKey) + { + if (!endpoint.IsAbsoluteUri || endpoint.Scheme != "http" || endpoint.Host != "127.0.0.1" || + endpoint.UserInfo.Length != 0 || endpoint.Query.Length != 0 || endpoint.Fragment.Length != 0 || + endpoint.AbsolutePath != "/api/v1/androidremote/owner/") + throw new ArgumentException("Ugyldig lokal ejeradresse / Invalid local owner address.", nameof(endpoint)); + this.client = client; + this.endpoint = endpoint; + this.ownerKey = ownerKey; + } + + public async Task GetAsync(CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + using var response = await SendAsync(request, cancellationToken); + return await response.Content.ReadFromJsonAsync(Wire.Json, cancellationToken) + ?? throw new InvalidDataException("Status mangler / Missing status."); + } + + public async Task BeginAsync(string name, IReadOnlyList permissions, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(endpoint, "pairings")) + { Content = JsonContent.Create(new BeginPairingRequest(name, permissions), options: Wire.Json) }; + using var response = await SendAsync(request, cancellationToken); + return await response.Content.ReadFromJsonAsync(Wire.Json, cancellationToken) + ?? throw new InvalidDataException("Parringsbevis mangler / Missing pairing offer."); + } + + public async Task RemoveAsync(string id, bool pending, CancellationToken cancellationToken = default) + { + if (!Guid.TryParseExact(id, "D", out var guid)) throw new ArgumentException("Ugyldigt id / Invalid ID.", nameof(id)); + using var request = new HttpRequestMessage(HttpMethod.Delete, new Uri(endpoint, + (pending ? "pairings/" : "devices/") + guid.ToString("D"))); + using var response = await SendAsync(request, cancellationToken, allowMissing: true); + } + + public async Task RevokeAllAsync(CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Delete, new Uri(endpoint, "access")); + using var response = await SendAsync(request, cancellationToken); + } + + private async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken, bool allowMissing = false) + { + // Bevidst ingen retry. Efter en mistet oprettelsesrespons skal ejeren opdatere listen. + // Deliberately no retry. After losing a creation response the owner must refresh the list. + request.Headers.Add("X-ControlHub-Owner", ownerKey); + var response = await client.SendAsync(request, cancellationToken); + if (response.IsSuccessStatusCode || (allowMissing && response.StatusCode == HttpStatusCode.NotFound)) return response; + response.Dispose(); + throw new HttpRequestException("Ejerhandlingen mislykkedes. Opdater listen. / Owner operation failed. Refresh the list.", null, response.StatusCode); + } +} diff --git a/Plugins/AndroidRemote/README.md b/Plugins/AndroidRemote/README.md index 3a02b71..de125b0 100644 --- a/Plugins/AndroidRemote/README.md +++ b/Plugins/AndroidRemote/README.md @@ -4,10 +4,10 @@ **Parring og adgangskontrol er implementeret som C#-bibliotek. Telefonapp og transport mangler.** Alt integrationskode ligger under denne mappe. RemoteDeviceRegistry håndterer enkeltbrugsparring, enhedsnøgler, rettigheder, udløb og tilbagekaldelse. RemoteCommandGateway kontrollerer adgang til den fælles dispatcher og status. RemotePermissions accepterer kun kendte PowerPoint- og OBS-handlinger. -Hosten registrerer AndroidRemotePlugin med modenhed development, tom handlingsliste og unavailable / transport_not_configured. Ingen nye HTTP-ruter eller netværksporte. Tests bruger simulerede enheder. Læs [design, test og næste trin](../../docs/androidremote.da.md). AndroidRemote er ejerens valgte nye Control Hub-klient til Android; tredjepartskompatibilitet er ikke implementeret. +Hosten registrerer AndroidRemotePlugin med modenhed development, tom handlingsliste og unavailable / transport_not_configured. Ejerens Windows-vindue ligger under `Desktop/` og de lokale ejerruter under `Host/`. Ingen telefonporte eller fjernadgang. Tests bruger simulerede enheder. Læs [design, test og næste trin](../../docs/androidremote.da.md). AndroidRemote er ejerens valgte nye Control Hub-klient til Android; tredjepartskompatibilitet er ikke implementeret. ## English **Pairing and authorization are implemented as a C# library. The phone app and transport remain unimplemented.** All integration code lives in this directory. RemoteDeviceRegistry handles single-use pairing, device credentials, permissions, expiry and revocation. RemoteCommandGateway authorizes access to the shared dispatcher and status. RemotePermissions accepts only known PowerPoint and OBS actions. -The host registers AndroidRemotePlugin with development maturity, no actions and unavailable / transport_not_configured. No new HTTP routes or listening ports. Tests use simulated devices. Read the [design, tests and next steps](../../docs/androidremote.en.md). AndroidRemote is the owner-selected new Control Hub client for Android; third-party compatibility is not implemented. +The host registers AndroidRemotePlugin with development maturity, no actions and unavailable / transport_not_configured. The Windows owner dialog lives under `Desktop/` and local owner routes under `Host/`. No phone listener or remote access. Tests use simulated devices. Read the [design, tests and next steps](../../docs/androidremote.en.md). AndroidRemote is the owner-selected new Control Hub client for Android; third-party compatibility is not implemented. diff --git a/Plugins/AndroidRemote/RemoteDeviceRegistry.cs b/Plugins/AndroidRemote/RemoteDeviceRegistry.cs index 7696f49..7a7c3b0 100644 --- a/Plugins/AndroidRemote/RemoteDeviceRegistry.cs +++ b/Plugins/AndroidRemote/RemoteDeviceRegistry.cs @@ -35,12 +35,13 @@ public sealed class RemoteDeviceRegistry(TimeProvider? timeProvider = null) private readonly Dictionary pending = new(StringComparer.Ordinal); private readonly Dictionary devices = new(StringComparer.Ordinal); - private sealed class Pending(string name, IReadOnlyList permissions, byte[] hash, long created) + private sealed class Pending(string name, IReadOnlyList permissions, byte[] hash, long created, DateTimeOffset expiresAt) { public string Name { get; } = name; public IReadOnlyList Permissions { get; } = permissions; public byte[] Hash { get; } = hash; public long Created { get; } = created; + public DateTimeOffset ExpiresAt { get; } = expiresAt; public int Attempts { get; set; } } private sealed record Paired(RemoteDevice Device, byte[] Hash, long Created); @@ -65,8 +66,9 @@ public PairingOffer BeginPairing(string deviceName, IEnumerable permissi throw new InvalidOperationException("Enhedsgrænsen er nået / Device limit reached."); var id = Guid.NewGuid().ToString("D"); var secret = NewSecret(); - pending.Add(id, new Pending(deviceName.Trim(), immutable, Hash(secret), clock.GetTimestamp())); - return new(id, secret, clock.GetUtcNow() + PairingLifetime); + var expiresAt = clock.GetUtcNow() + PairingLifetime; + pending.Add(id, new Pending(deviceName.Trim(), immutable, Hash(secret), clock.GetTimestamp(), expiresAt)); + return new(id, secret, expiresAt); } } @@ -108,6 +110,15 @@ public IReadOnlyList ListDevices() } public int PendingCount { get { lock (sync) { Prune(); return pending.Count; } } } + public RemoteOwnerSnapshot GetOwnerSnapshot() + { + lock (sync) + { + Prune(); + return new(false, devices.Values.Select(d => d.Device).ToArray(), + pending.Select(p => new PendingPairing(p.Key, p.Value.Name, p.Value.Permissions, p.Value.ExpiresAt)).ToArray()); + } + } public bool CancelPairing(string pairingId) { lock (sync) return RemovePending(pairingId); } public bool RevokeDevice(string deviceId) { lock (sync) return RemoveDevice(deviceId); } public void RevokeAll() diff --git a/README.en.md b/README.en.md index 8882a26..ed8a315 100644 --- a/README.en.md +++ b/README.en.md @@ -28,7 +28,7 @@ The goal is to give operators clear buttons, predictable commands and truthful s | 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 | Tested library for pairing, device permissions, expiry, revocation and command authorization | No Android app, pairing dialog or phone transport yet | +| AndroidRemote | Windows invitation and revocation dialog, local owner routes and tested device authorization | No Android app or phone transport yet | | 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. diff --git a/README.md b/README.md index 5039125..4397c73 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Formålet er at give operatøren tydelige knapper, forudsigelige kommandoer og | 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 | Testet bibliotek til parring, enhedsrettigheder, udløb, tilbagekaldelse og kommandokontrol | Ingen Android-app, parringsdialog eller telefontransport endnu | +| AndroidRemote | Windows-vindue til parringsbeviser og tilbagekaldelse, lokale ejerruter og testet enhedsadgang | Ingen Android-app eller telefontransport endnu | | 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. diff --git a/docs/androidremote.da.md b/docs/androidremote.da.md index 4c6f158..56f7ef0 100644 --- a/docs/androidremote.da.md +++ b/docs/androidremote.da.md @@ -6,7 +6,7 @@ Første kodetrin er et transportuafhængigt .NET 10-bibliotek under `Plugins/And ## Parringsforløb -1. En fremtidig lokal ejergrænseflade kalder `BeginPairing` med et navn på 1–80 tegn uden kontroltegn og en eksplicit rettighedsliste. +1. Kontrolvinduets **Administrér telefonadgang** kalder `BeginPairing` med et navn på 1–80 tegn uden kontroltegn og en eksplicit rettighedsliste. 2. Biblioteket returnerer et parrings-id, et tilfældigt bevis og udløbstidspunkt. Beviset er 32 kryptografisk tilfældige bytes gengivet som 64 hextegn; det er ikke en kort PIN-kode. Det gælder i to minutter. 3. Den fremtidige telefontransport afleverer id og bevis til `CompletePairing`. Højst ét samtidigt forsøg kan lykkes. Fem forkerte forsøg annullerer parringen; ugyldigt formaterede beviser tæller også. 4. Vellykket parring giver et nyt enheds-id og en uafhængig nøgle, som gælder i otte timer. Navn og rettigheder kommer fra ejerens valg; telefonen kan ikke udvide dem. @@ -39,9 +39,9 @@ Klientens kommando-UUID mappes deterministisk til et internt UUID i parringens e ## Før telefonbrug -Der mangler lokal parringsdialog/enhedsliste, en dansk/engelsk Android-klient og særskilt TLS-transport med verificeret serveridentitet, sikker overførsel af parringsbevis/nøgle og sikker lagring på telefonen. Transporten skal begrænse størrelse, samtidighed og forespørgselshastighed; bibliotekets parringsgrænser erstatter ikke dette. Derefter følger transporttests og fysisk Android-test. +Der mangler en dansk/engelsk Android-klient og særskilt TLS-transport med verificeret serveridentitet, sikker overførsel af parringsbevis/nøgle og sikker lagring på telefonen. Transporten skal begrænse størrelse, samtidighed og forespørgselshastighed; bibliotekets parringsgrænser erstatter ikke dette. Derefter følger transporttests og fysisk Android-test. -Der er ingen nye HTTP-endpoints. Parring og tilbagekaldelse er ejerfunktioner i biblioteket, ikke anonyme telefon-API'er. Det lokale Control Hub-token skal ikke kopieres til telefonen. Hosten lytter fortsat kun på loopback; der åbnes ingen firewall eller LAN-adgang. Pluginstatus er `unavailable` / `transport_not_configured` med tom handlingsliste. +Kontrolvinduet bruger [lokale ejerruter](protocol.da.md). De kræver både hostens forbindelsesnøgle og en særskilt tilfældig ejernøgle, som kun gælder denne opstart. Stream Deck-nøglen alene kan ikke administrere adgang. Der er endnu ingen rute, hvor en telefon kan indløse beviset. Det lokale Control Hub-token skal ikke kopieres til telefonen. Hosten lytter fortsat kun på loopback; der åbnes ingen firewall eller LAN-adgang. Pluginstatus er `unavailable` / `transport_not_configured` med tom handlingsliste. ## Test diff --git a/docs/androidremote.en.md b/docs/androidremote.en.md index 8539b4c..4e7f817 100644 --- a/docs/androidremote.en.md +++ b/docs/androidremote.en.md @@ -6,7 +6,7 @@ The first implementation is a transport-independent .NET 10 library under `Plugi ## Pairing flow -1. A future local owner interface calls `BeginPairing` with a 1–80 character name without control characters and an explicit permission list. +1. The control window’s **Manage phone access** dialog calls `BeginPairing` with a 1–80 character name without control characters and an explicit permission list. 2. The library returns a pairing ID, random secret and expiry time. The secret is 32 cryptographically random bytes represented by 64 hexadecimal characters, not a short PIN. It lasts two minutes. 3. The future phone transport submits the ID and secret to `CompletePairing`. At most one concurrent attempt succeeds. Five incorrect attempts cancel the pairing; malformed secrets count too. 4. Successful pairing issues a new device ID and independent token lasting eight hours. The name and permissions come from the owner's selection; the phone cannot expand them. @@ -39,9 +39,9 @@ The client's command UUID is deterministically mapped to an internal UUID in the ## Before phone use -Remaining work includes a local pairing dialog/device list, a Danish/English Android client and separate TLS transport with verified server identity, secure pairing-secret/token transfer and secure storage on the phone. The transport must limit size, concurrency and request rate; library pairing limits do not replace these. Transport tests and physical Android testing must follow. +Remaining work includes a Danish/English Android client and separate TLS transport with verified server identity, secure pairing-secret/token transfer and secure storage on the phone. The transport must limit size, concurrency and request rate; library pairing limits do not replace these. Transport tests and physical Android testing must follow. -There are no new HTTP endpoints. Pairing and revocation are owner operations in the library, not anonymous phone APIs. The local Control Hub token must not be copied to the phone. The host still listens only on loopback; no firewall or LAN access is opened. Plugin status is `unavailable` / `transport_not_configured` with an empty action list. +The control window uses [local owner routes](protocol.en.md). They require both the host connection key and a separate random owner key for this launch. The Stream Deck key alone cannot manage access. There is no route for a phone to redeem an invitation yet. The local Control Hub token must not be copied to the phone. The host still listens only on loopback; no firewall or LAN access is opened. Plugin status is `unavailable` / `transport_not_configured` with an empty action list. ## Tests diff --git a/docs/installation.da.html b/docs/installation.da.html index b51ebe0..809827d 100644 --- a/docs/installation.da.html +++ b/docs/installation.da.html @@ -1,12 +1,13 @@ Control Hub – installation English

      Control Hub 0.0.001

      Installationsvejledning til Windows x64 · udviklingsversion

      -

      Stream Deck → PowerPoint og OBS er første prioritet. AndroidRemote og de øvrige enhedsintegrationer er endnu kun forberedt. Installationspakken er ikke en godkendelse af praktisk afvikling.

      +

      Stream Deck → PowerPoint og OBS er første prioritet. AndroidRemote har nu et lokalt vindue til telefonadgang. Telefonappen og telefonforbindelsen mangler endnu. Installationspakken er ikke en godkendelse af praktisk afvikling.

      1. Installér

      1. Åbn ControlHub-0.0.001-win-x64-Setup.exe, og vælg Dansk. Programmet installeres for din Windows-bruger og har en almindelig afinstalleringsfunktion.
      2. .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.
      3. Å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

      1. Aktivér OBS' WebSocket-server i OBS, og aflæs port og adgangskode. Brug WebSocket-adgangskoden, ikke streamingnøglen.
      2. Indtast adressen, normalt ws://127.0.0.1:4455, og adgangskoden i Control Hub. Tryk Gem indstillinger.
      3. 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

      1. 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.
      2. 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.
      3. Træk Status, Næste slide, Forrige slide og Skift scene fra gruppen Control Hub til en testprofil.
      4. 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.
      5. 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

      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. Det er endnu ikke muligt at tilslutte en rigtig telefon. 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.
      diff --git a/docs/installation.en.html b/docs/installation.en.html index e151610..b5493b6 100644 --- a/docs/installation.en.html +++ b/docs/installation.en.html @@ -1,12 +1,13 @@ 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 and the other device integrations are only planned. This installation package does not establish acceptance for live operation.

      +

      Stream Deck → PowerPoint and OBS is the first priority. AndroidRemote now has a local phone access dialog. The phone app and phone connection are not available yet. This installation package does not establish acceptance for live operation.

      1. Install

      1. Open ControlHub-0.0.001-win-x64-Setup.exe and select English. It installs for your Windows user and includes a standard uninstaller.
      2. .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.
      3. 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

      1. Enable OBS' WebSocket server in OBS and check its port and password. Use the WebSocket password, not your streaming key.
      2. Enter the address, usually ws://127.0.0.1:4455, and password in Control Hub. Click Save settings.
      3. Click Start Control Hub. Status reports PowerPoint and OBS connectivity separately. Check connection only reads status.

      3. Install the Stream Deck keys

      1. Click Install Stream Deck plugin in Control Hub and complete Stream Deck's installation dialog. Alternatively, double-click the included dk.thebonden.controlhub.streamDeckPlugin.
      2. 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.
      3. Drag Status, Next slide, Previous slide and Switch scene from the Control Hub group onto a test profile.
      4. 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.
      5. 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

      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. A real phone cannot connect yet. 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.
      diff --git a/docs/project.da.md b/docs/project.da.md index 8f7ad20..f59ba7d 100644 --- a/docs/project.da.md +++ b/docs/project.da.md @@ -99,4 +99,4 @@ Alle ændringer går gennem PR til `main`. Versionen angives til brugeren som ** ## 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. Telefonapp, ejerens parringsdialog og TLS-transport mangler fortsat. Hosten viser dette som utilgængelig transport og åbner ingen fjernadgang. Se [design og afgrænsning](androidremote.da.md). +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. Android-appen og TLS-transporten mangler fortsat. Hosten viser dette som utilgængelig transport og åbner ingen fjernadgang. Se [design og afgrænsning](androidremote.da.md). diff --git a/docs/project.en.md b/docs/project.en.md index d1b8306..c1df421 100644 --- a/docs/project.en.md +++ b/docs/project.en.md @@ -99,4 +99,4 @@ All changes go through a PR to `main`. The user-facing version is **0.0.001**; t ## 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 phone app, owner pairing dialog and TLS transport remain unimplemented. The host reports unavailable transport and opens no remote access. See the [design and scope](androidremote.en.md). +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. The Android app and TLS transport remain unimplemented. The host reports unavailable transport and opens no remote access. See the [design and scope](androidremote.en.md). diff --git a/docs/protocol.da.md b/docs/protocol.da.md index 6e04576..01ba8a0 100644 --- a/docs/protocol.da.md +++ b/docs/protocol.da.md @@ -90,4 +90,18 @@ OBS-afbrydelse eller et ugyldigt svar efter påbegyndt afsendelse giver `outcome ## AndroidRemote-bibliotek -AndroidRemote annoncerer nu modenhed `development`, tom handlingsliste og `unavailable` med `data.reason = transport_not_configured`. Biblioteket har ingen HTTP-ruter endnu. 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). +AndroidRemote annoncerer nu modenhed `development`, tom handlingsliste og `unavailable` med `data.reason = transport_not_configured`. Telefontransporten har ingen HTTP-ruter endnu. 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: false`, `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 index 1dd8223..1dfc59c 100644 --- a/docs/protocol.en.md +++ b/docs/protocol.en.md @@ -90,4 +90,18 @@ An OBS disconnect or invalid reply after starting request transmission produces ## AndroidRemote library -AndroidRemote now advertises `development` maturity, no actions and `unavailable` with `data.reason = transport_not_configured`. The library has no HTTP routes yet. 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). +AndroidRemote now advertises `development` maturity, no actions and `unavailable` with `data.reason = transport_not_configured`. The phone transport has no HTTP routes yet. 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: false`, `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/testing.da.md b/docs/testing.da.md index 5ceb3bc..18eba7a 100644 --- a/docs/testing.da.md +++ b/docs/testing.da.md @@ -62,4 +62,8 @@ Den 1. november består 51 C#-tests og 27 JavaScript-tests efter tilføjelse af ## 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. +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 + +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 index 721d85e..2d42b41 100644 --- a/docs/testing.en.md +++ b/docs/testing.en.md @@ -62,4 +62,8 @@ On 1 November, 51 C# tests and 27 JavaScript tests pass after adding specific co ## 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. +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 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/src/ControlHub.Desktop/ControlHub.Desktop.csproj b/src/ControlHub.Desktop/ControlHub.Desktop.csproj index 23c0097..9bfec31 100644 --- a/src/ControlHub.Desktop/ControlHub.Desktop.csproj +++ b/src/ControlHub.Desktop/ControlHub.Desktop.csproj @@ -6,4 +6,7 @@ true ControlHub + + +
      diff --git a/src/ControlHub.Desktop/HostSession.cs b/src/ControlHub.Desktop/HostSession.cs index b5d332e..9fbeb65 100644 --- a/src/ControlHub.Desktop/HostSession.cs +++ b/src/ControlHub.Desktop/HostSession.cs @@ -1,4 +1,6 @@ using System.Diagnostics; +using System.Security.Cryptography; +using ControlHub.Plugins.AndroidRemote; using System.Net; using System.Net.Http.Headers; using System.Net.Sockets; @@ -10,7 +12,11 @@ namespace ControlHub.Desktop; internal sealed class HostSession : IDisposable { private Process? process; - private readonly HttpClient client = new() { Timeout = TimeSpan.FromSeconds(35) }; + 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 string apiBase; public bool IsRunning => process is { HasExited: false }; @@ -45,6 +51,8 @@ public async Task StartAsync(Settings settings) 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_OBS_URL"] = settings.ObsUrl; start.Environment["CONTROLHUB_OBS_PASSWORD"] = settings.ObsPassword; @@ -84,6 +92,7 @@ public async Task StatusAsync() public async Task StopAsync() { + ownerKey = null; if (!IsRunning) return; process!.StandardInput.Close(); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); diff --git a/src/ControlHub.Desktop/MainWindow.cs b/src/ControlHub.Desktop/MainWindow.cs index 5108632..ce75c37 100644 --- a/src/ControlHub.Desktop/MainWindow.cs +++ b/src/ControlHub.Desktop/MainWindow.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using ControlHub.Plugins.AndroidRemote.Desktop; namespace ControlHub.Desktop; @@ -22,6 +23,7 @@ internal sealed class MainWindow : Form 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 bool busy, closing, canClose; private bool Danish => language.SelectedIndex != 1; private string T(string da, string en) => Danish ? da : en; @@ -52,6 +54,7 @@ public MainWindow() 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; }); @@ -59,6 +62,13 @@ public MainWindow() start.Click += async (_, _) => await RunAsync(async () => { SaveSettings(); await host.StartAsync(settings); 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) => @@ -94,6 +104,7 @@ private void Translate() 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"); + phones.Text = T("Administrér telefonadgang", "Manage phone access"); UpdateEnabled(); } @@ -137,7 +148,7 @@ private void UpdateEnabled() { var running = host.IsRunning; start.Enabled = save.Enabled = obsUrl.Enabled = obsPassword.Enabled = !busy && !running; - stop.Enabled = refresh.Enabled = !busy && running; + stop.Enabled = refresh.Enabled = phones.Enabled = !busy && running; copy.Enabled = install.Enabled = guide.Enabled = language.Enabled = !busy; } diff --git a/src/ControlHub.Desktop/PackageSelfTest.cs b/src/ControlHub.Desktop/PackageSelfTest.cs index 47ed389..5f37f2e 100644 --- a/src/ControlHub.Desktop/PackageSelfTest.cs +++ b/src/ControlHub.Desktop/PackageSelfTest.cs @@ -55,6 +55,15 @@ public static async Task RunAsync(string outputDirectory) remote.GetProperty("data").GetProperty("reason").GetString() != "transport_not_configured") throw new InvalidDataException("AndroidRemote capability status failed"); checks.Add("AndroidRemote library reports unavailable phone transport"); + 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"); + await owner.RemoveAsync(invite.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"); } diff --git a/src/ControlHub.Host/ControlHub.Host.csproj b/src/ControlHub.Host/ControlHub.Host.csproj index aa35259..4a562aa 100644 --- a/src/ControlHub.Host/ControlHub.Host.csproj +++ b/src/ControlHub.Host/ControlHub.Host.csproj @@ -1,5 +1,6 @@ + diff --git a/src/ControlHub.Host/Program.cs b/src/ControlHub.Host/Program.cs index bd8ce34..1b14465 100644 --- a/src/ControlHub.Host/Program.cs +++ b/src/ControlHub.Host/Program.cs @@ -6,6 +6,7 @@ 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; @@ -73,6 +74,9 @@ 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(new RemoteDeviceRegistry(), 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) => 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/host-smoke.cjs b/tests/host-smoke.cjs index 95e9e3f..53242f6 100644 --- a/tests/host-smoke.cjs +++ b/tests/host-smoke.cjs @@ -2,8 +2,9 @@ const assert = require("node:assert/strict"); const { spawn } = require("node:child_process"); const { randomBytes, randomUUID } = require("node:crypto"); const token = randomBytes(32).toString("hex"); +const ownerKey = randomBytes(32).toString("hex"); const child = spawn("dotnet", ["src/ControlHub.Host/bin/Release/net10.0/ControlHub.Host.dll"], - { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_PORT: "0", CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); + { env: { ...process.env, CONTROLHUB_TOKEN: token, CONTROLHUB_OWNER_KEY: ownerKey, CONTROLHUB_PORT: "0", CONTROLHUB_OBS_URL: "ws://127.0.0.1:1" }, stdio: ["ignore", "pipe", "pipe"] }); let log = ""; let base; child.stdout.on("data", d => { @@ -28,6 +29,7 @@ const post = body => fetch(base + "commands", {method:"POST",headers,body:JSON.s 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:{}}; 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); +}; From 2c5f94d51abb84b619abe709e7468b213cdac6c3 Mon Sep 17 00:00:00 2001 From: thebonden <51397557+thebonden@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:14:18 +0100 Subject: [PATCH 08/10] Par AndroidRemote over HTTPS og byg APK / Pair AndroidRemote over HTTPS and build APK --- .github/workflows/ci.yml | 20 ++ .gitignore | 21 +- CHANGELOG.md | 34 +-- .../AndroidRemote/Android/AndroidManifest.xml | 10 + Plugins/AndroidRemote/Android/build.py | 65 ++++++ .../Android/src/PinnedChannel.java | 101 +++++++++ .../Android/src/RemoteActivity.java | 194 ++++++++++++++++++ .../Android/src/SessionStore.java | 41 ++++ Plugins/AndroidRemote/AndroidRemotePlugin.cs | 11 +- .../Desktop/PhoneAccessWindow.cs | 27 ++- Plugins/AndroidRemote/Host/PhoneServer.cs | 151 ++++++++++++++ Plugins/AndroidRemote/PhoneEndpoint.cs | 21 ++ Plugins/AndroidRemote/README.md | 8 +- Plugins/AndroidRemote/RemoteDeviceRegistry.cs | 24 ++- README.en.md | 2 +- README.md | 2 +- docs/androidremote.da.md | 51 ++--- docs/androidremote.en.md | 51 ++--- docs/installation.da.html | 4 +- docs/installation.en.html | 4 +- docs/project.da.md | 6 +- docs/project.en.md | 6 +- docs/protocol.da.md | 42 ++-- docs/protocol.en.md | 42 ++-- docs/testing.da.md | 2 + docs/testing.en.md | 2 + scripts/android-emulator-ci.sh | 26 +++ src/ControlHub.Desktop/HostSession.cs | 14 +- src/ControlHub.Desktop/MainWindow.cs | 16 +- src/ControlHub.Desktop/PackageSelfTest.cs | 42 +++- src/ControlHub.Host/Program.cs | 16 +- tests/PhoneHarness/PhoneHarness.csproj | 8 + tests/PhoneHarness/Program.cs | 66 ++++++ tests/android-ui/AndroidManifest.xml | 5 + tests/android-ui/run.py | 73 +++++++ tests/android-ui/src/PhoneTrial.java | 75 +++++++ 36 files changed, 1107 insertions(+), 176 deletions(-) create mode 100644 Plugins/AndroidRemote/Android/AndroidManifest.xml create mode 100644 Plugins/AndroidRemote/Android/build.py create mode 100644 Plugins/AndroidRemote/Android/src/PinnedChannel.java create mode 100644 Plugins/AndroidRemote/Android/src/RemoteActivity.java create mode 100644 Plugins/AndroidRemote/Android/src/SessionStore.java create mode 100644 Plugins/AndroidRemote/Host/PhoneServer.cs create mode 100644 Plugins/AndroidRemote/PhoneEndpoint.cs create mode 100644 scripts/android-emulator-ci.sh create mode 100644 tests/PhoneHarness/PhoneHarness.csproj create mode 100644 tests/PhoneHarness/Program.cs create mode 100644 tests/android-ui/AndroidManifest.xml create mode 100644 tests/android-ui/run.py create mode 100644 tests/android-ui/src/PhoneTrial.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b7c689..f546728 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,3 +43,23 @@ jobs: path: artifacts/windows/files/* retention-days: 14 if-no-files-found: error + android: + name: Android APK and emulator / APK og emulator + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - run: bash scripts/android-emulator-ci.sh + - uses: actions/upload-artifact@v4 + with: + name: ControlHub-AndroidRemote-0.0.001-development + path: ${{ runner.temp }}/controlhub-android/ControlHub-AndroidRemote-0.0.001.apk + retention-days: 14 + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 34bd8da..ec0a0f1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,13 @@ -**/bin/ -**/obj/ -.vs/ -TestResults/ -artifacts/ -.env -*.user -*.streamDeckPlugin +**/bin/ +**/obj/ +.vs/ +TestResults/ +artifacts/ +.env +*.user +*.streamDeckPlugin +*.apk +*.p12 +*.jks +*.controlhub +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 71acdce..6be5b62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,19 +2,20 @@ ## 0.0.001 — udviklingsversion / development version -### Dansk -- Nyt Windows-vindue **Administrér telefonadgang**: vælg rettigheder, opret et to-minutters bevis, se ventende/parrede enheder og tilbagekald adgang. Lokale ejerruter kræver en separat nøgle for hver opstart; Stream Deck-nøglen alene er utilstrækkelig. Android-app og telefontransport mangler stadig. -- AndroidRemote-bibliotek med enkeltbrugsparring, enhedsrettigheder, udløb og tilbagekaldelse. Ingen telefonapp eller transport endnu. +### Dansk +- AndroidRemote til Android 8 og nyere med parret HTTPS, certifikatkontrol, krypteret enhedsnøgle, slides, OBS-scene og status. APK-knapperne er prøvet på en Android 15-emulator med bogførte kommandoer, afbrydelse og tilbagekaldelse. +- Nyt Windows-vindue **Administrér telefonadgang**: vælg rettigheder, opret et to-minutters bevis, se ventende/parrede enheder og tilbagekald adgang. Lokale ejerruter kræver en separat nøgle for hver opstart; Stream Deck-nøglen alene er utilstrækkelig. +- AndroidRemote-bibliotek med enkeltbrugsparring, enhedsrettigheder, udløb og tilbagekaldelse. - Adgang kontrolleres igen efter kommandokøen; kommandosvar holdes adskilt pr. parret enhed. - Host-smoketest bruger en separat lokal port, så den åbne Control Hub kan fortsætte. -- Konkrete forbindelsesårsager for PowerPoint og OBS i status og Stream Deck, med sikre dansk/engelske tekster. -- Afbrudte OBS-kommandoer efter påbegyndt afsendelse rapporteres som ukendt udfald; aldrig automatisk genafsendelse. -- Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. +- Konkrete forbindelsesårsager for PowerPoint og OBS i status og Stream Deck, med sikre dansk/engelske tekster. +- Afbrudte OBS-kommandoer efter påbegyndt afsendelse rapporteres som ukendt udfald; aldrig automatisk genafsendelse. +- Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. - Windows x64-installation med inkluderet .NET og officiel Stream Deck-installationspakke. - Dansk/engelsk kontrolvindue med start/stop, forbindelsesstatus, kopiering af vedvarende token og DPAPI-krypterede OBS-indstillinger. - Pakketest af konfiguration, lokal host og stop; Windows-artefakter i CI uden release/tag. -- Forbindelsestest i Stream Deck-indstillingerne med separat status for Control Hub, PowerPoint og OBS. -- Beskyttelse mod forsinket knapfeedback efter profil-/indstillingsskift. +- Forbindelsestest i Stream Deck-indstillingerne med separat status for Control Hub, PowerPoint og OBS. +- Beskyttelse mod forsinket knapfeedback efter profil-/indstillingsskift. - Hovedikon i krævet PNG-format og officiel Elgato-validering i CI. - C#/.NET 10-kontrakter, dispatcher og lokal autentificeret HTTP-host. - Eksplicit pluginsystem med ærlig status for ikke-implementerede integrationer. @@ -25,19 +26,20 @@ - Automatiske tests, CI på Windows/Linux og projektbeskrivelse på begge sprog. - Fysisk test i det aktive miljø afventer. Ingen release eller tag. -### English -- New Windows **Manage phone access** dialog: select permissions, create a two-minute invitation, list pending/paired devices and revoke access. Local owner routes require a separate key for each launch; the Stream Deck key alone is insufficient. Android app and phone transport remain unimplemented. -- AndroidRemote library with single-use pairing, device permissions, expiry and revocation. No phone app or transport yet. +### English +- AndroidRemote for Android 8 and later with paired HTTPS, certificate verification, encrypted device credentials, slides, OBS scene and status. Android 15 emulator tests exercise the APK controls, counted commands, disconnection and revocation. +- New Windows **Manage phone access** dialog: select permissions, create a two-minute invitation, list pending/paired devices and revoke access. Local owner routes require a separate key for each launch; the Stream Deck key alone is insufficient. +- AndroidRemote library with single-use pairing, device permissions, expiry and revocation. - Authorization is rechecked after queueing; command results are isolated per paired device. - Host smoke tests use a separate local port so the open Control Hub can keep running. -- Specific PowerPoint/OBS connection reasons in status and Stream Deck, with safe Danish/English messages. -- OBS commands interrupted after transmission starts report an unknown outcome; no automatic retries. -- Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. +- Specific PowerPoint/OBS connection reasons in status and Stream Deck, with safe Danish/English messages. +- OBS commands interrupted after transmission starts report an unknown outcome; no automatic retries. +- Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. - Windows x64 installer with included .NET and an official Stream Deck installation package. - Danish/English control window with start/stop, connection status, persistent token copying and DPAPI-encrypted OBS settings. - Package checks for configuration, local host and shutdown; Windows CI artifacts without a release/tag. -- Connection check in Stream Deck settings with separate Control Hub, PowerPoint and OBS status. -- Protection against late key feedback after profile/settings changes. +- Connection check in Stream Deck settings with separate Control Hub, PowerPoint and OBS status. +- Protection against late key feedback after profile/settings changes. - Main icon in the required PNG format and official Elgato validation in CI. - C#/.NET 10 contracts, dispatcher and authenticated local HTTP host. - Explicit plugin system with truthful status for unimplemented integrations. diff --git a/Plugins/AndroidRemote/Android/AndroidManifest.xml b/Plugins/AndroidRemote/Android/AndroidManifest.xml new file mode 100644 index 0000000..83598e8 --- /dev/null +++ b/Plugins/AndroidRemote/Android/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/Plugins/AndroidRemote/Android/build.py b/Plugins/AndroidRemote/Android/build.py new file mode 100644 index 0000000..0f00771 --- /dev/null +++ b/Plugins/AndroidRemote/Android/build.py @@ -0,0 +1,65 @@ +"""Build and verify the development APK with the Android SDK and a JDK.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile +import zipfile + +ROOT = Path(__file__).resolve().parent +APP_ID = "dk.thebonden.controlhub.remote" + + +def build(source, manifest, output, android_sdk, jdk, keystore): + sdk = android_sdk / "build-tools" / "36.0.0" + platform = android_sdk / "platforms" / "android-35" / "android.jar" + executable = ".exe" if os.name == "nt" else "" + java = jdk / "bin" / ("java" + executable) + + def run(*args): + subprocess.run([str(arg) for arg in args], check=True) + + output.parent.mkdir(parents=True, exist_ok=True) + keystore.parent.mkdir(parents=True, exist_ok=True) + if not keystore.exists(): + run(jdk / "bin" / ("keytool" + executable), "-genkeypair", "-keystore", keystore, + "-storepass", "android", "-keypass", "android", "-alias", "androiddebugkey", + "-keyalg", "RSA", "-keysize", "2048", "-validity", "3650", "-dname", "CN=Control Hub Development") + + with tempfile.TemporaryDirectory(dir=output.parent) as temp: + work = Path(temp) + classes = work / "classes" + classes.mkdir() + run(jdk / "bin" / ("javac" + executable), "-encoding", "UTF-8", "-source", "8", "-target", "8", + "-classpath", platform, "-d", classes, *sorted(source.rglob("*.java"))) + jar = work / "classes.jar" + with zipfile.ZipFile(jar, "w") as archive: + for entry in classes.rglob("*.class"): + archive.write(entry, entry.relative_to(classes).as_posix()) + run(java, "-cp", sdk / "lib/d8.jar", "com.android.tools.r8.D8", "--min-api", "26", + "--lib", platform, "--output", work, jar) + unsigned = work / "unsigned.apk" + run(sdk / ("aapt2" + executable), "link", "-o", unsigned, "-I", platform, "--manifest", manifest) + with zipfile.ZipFile(unsigned, "a", compression=zipfile.ZIP_DEFLATED) as archive: + archive.write(work / "classes.dex", "classes.dex") + aligned = work / "aligned.apk" + run(sdk / ("zipalign" + executable), "-f", "4", unsigned, aligned) + signed = work / "signed.apk" + signer = sdk / "lib/apksigner.jar" + run(java, "-jar", signer, "sign", "--ks", keystore, "--ks-pass", "pass:android", + "--ks-key-alias", "androiddebugkey", "--out", signed, aligned) + run(java, "-jar", signer, "verify", "--verbose", signed) + signed.replace(output) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--sdk", type=Path, required=True) + parser.add_argument("--jdk", type=Path, required=True) + parser.add_argument("--keystore", type=Path, required=True, help="Development signing key outside the repository") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--ui-test", action="store_true") + args = parser.parse_args() + module = ROOT.parents[2] / "tests" / "android-ui" if args.ui_test else ROOT + build(module / "src", module / "AndroidManifest.xml", args.out.resolve(), + args.sdk.resolve(), args.jdk.resolve(), args.keystore.resolve()) diff --git a/Plugins/AndroidRemote/Android/src/PinnedChannel.java b/Plugins/AndroidRemote/Android/src/PinnedChannel.java new file mode 100644 index 0000000..2b6f6b4 --- /dev/null +++ b/Plugins/AndroidRemote/Android/src/PinnedChannel.java @@ -0,0 +1,101 @@ +package dk.thebonden.controlhub.remote; + +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.security.cert.*; +import javax.net.ssl.*; +import org.json.*; + +final class PinnedChannel { + static final class Denied extends IOException { + final int status; + Denied(int status) { super("HTTP " + status); this.status = status; } + } + private final URI endpoint; + private final SSLSocketFactory sockets; + + PinnedChannel(JSONObject transport) throws Exception { + endpoint = new URI(transport.getString("endpoint")); + String host = endpoint.getHost(); + if (!"https".equals(endpoint.getScheme()) || host == null || !privateIPv4(host) + || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null || endpoint.getRawFragment() != null + || !(endpoint.getPath().isEmpty() || "/".equals(endpoint.getPath()))) + throw new IllegalArgumentException("endpoint"); + String pin = transport.getString("certificateSha256"); + if (!pin.matches("[0-9A-Fa-f]{64}")) throw new IllegalArgumentException("pin"); + byte[] expected = new byte[32]; + for (int i = 0; i < expected.length; i++) expected[i] = (byte)Integer.parseInt(pin.substring(i*2, i*2+2),16); + X509TrustManager trust = new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } + public void checkClientTrusted(X509Certificate[] chain, String auth) throws CertificateException { + throw new CertificateException("client"); + } + public void checkServerTrusted(X509Certificate[] chain, String auth) throws CertificateException { + if (chain == null || chain.length == 0) throw new CertificateException("empty"); + chain[0].checkValidity(); + try { + byte[] actual = MessageDigest.getInstance("SHA-256").digest(chain[0].getEncoded()); + if (!MessageDigest.isEqual(expected, actual)) throw new CertificateException("identity"); + } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } + } + }; + SSLContext tls = SSLContext.getInstance("TLS"); + tls.init(null,new TrustManager[]{trust},null); + sockets = tls.getSocketFactory(); + } + + private static boolean privateIPv4(String host) { + String[] parts = host.split("\\.", -1); + if (parts.length != 4) return false; + int[] bytes = new int[4]; + for (int i=0; i<4; i++) { + if (!parts[i].matches("0|[1-9][0-9]{0,2}")) return false; + bytes[i] = Integer.parseInt(parts[i]); + if (bytes[i] > 255) return false; + } + return host.equals("127.0.0.1") || bytes[0]==10 || (bytes[0]==172 && bytes[1]>=16 && bytes[1]<=31) + || (bytes[0]==192 && bytes[1]==168); + } + + JSONObject request(String route, JSONObject body, JSONObject session) throws Exception { + URL url = endpoint.resolve("/phone/v1/" + route).toURL(); + HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(Proxy.NO_PROXY); + try { + connection.setSSLSocketFactory(sockets); + // Default hostname verification also checks the IP subject alternative name. + connection.setInstanceFollowRedirects(false); + connection.setUseCaches(false); + connection.setConnectTimeout(6000); + connection.setReadTimeout(35000); + if (session != null) { + connection.setRequestProperty("X-ControlHub-Device", session.getString("id")); + connection.setRequestProperty("Authorization", "Bearer " + session.getString("token")); + } + if (body != null) { + byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setFixedLengthStreamingMode(bytes.length); + connection.setRequestProperty("Content-Type","application/json"); + try (OutputStream out = connection.getOutputStream()) { out.write(bytes); } + } + int status = connection.getResponseCode(); + if (status != 200) throw new Denied(status); + try (InputStream in = connection.getInputStream()) { return new JSONObject(read(in, 256 * 1024)); } + } finally { connection.disconnect(); } + } + + static String read(InputStream in, int limit) throws IOException { + if (in == null) throw new IOException("missing input"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + for (int count; (count = in.read(buffer)) != -1;) { + if (count > limit - out.size()) throw new IOException("size"); + out.write(buffer,0,count); + } + return out.toString("UTF-8"); + } +} diff --git a/Plugins/AndroidRemote/Android/src/RemoteActivity.java b/Plugins/AndroidRemote/Android/src/RemoteActivity.java new file mode 100644 index 0000000..3fe9227 --- /dev/null +++ b/Plugins/AndroidRemote/Android/src/RemoteActivity.java @@ -0,0 +1,194 @@ +package dk.thebonden.controlhub.remote; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.text.InputFilter; +import android.text.InputType; +import android.view.*; +import android.widget.*; +import java.io.InputStream; +import java.util.*; +import java.util.concurrent.*; +import org.json.*; +import javax.net.ssl.SSLException; + +public final class RemoteActivity extends Activity { + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final ArrayList