From d2d95571003b04094faecb02d563425770adfe47 Mon Sep 17 00:00:00 2001 From: Jasper Miller-Waugh Date: Thu, 26 Nov 2026 16:37:08 +1300 Subject: [PATCH 1/7] Serve haptics over plain HTTP on loopback, deprecate HTTPS Browsers now treat 127.0.0.1 as a secure context, so the shared local.jmw.nz certificate is no longer needed outside Safari. The plugin now serves the API on http://127.0.0.1:41080 (started before the certificate download) and keeps https://local.jmw.nz:41443 as a deprecated Safari fallback until Safari allows loopback requests, or November 2027 at the latest. The web client tries HTTP first and falls back to HTTPS, and the docs lead with HTTP. Also from the Marketplace security review: oversized HTTP requests and WebSocket frames or messages now drop the connection before NetCoreServer buffers them (one 200 MB frame previously grew Logi Plugin Service by ~790 MB), upgrades are limited to /ws, GET / no longer reports version or endpoint details, 500s no longer echo exception text, and the listing discloses that any website can trigger haptics. Version bumped to 1.3. --- README.md | 57 ++-- src/HapticWebPlugin.cs | 87 +++--- src/Helpers/HapticEndpoint.cs | 205 +++++++++++++ src/Helpers/HttpsServer.cs | 275 ------------------ src/Helpers/LocalServer.cs | 256 ++++++++++++++++ src/package/metadata/LoupedeckPackage.yaml | 4 +- .../src/lib/components/ApiReference.svelte | 6 +- web-demo/src/lib/config.ts | 22 +- web-demo/src/lib/haptics-ws.ts | 44 ++- web-demo/src/lib/haptics.ts | 46 ++- web-demo/src/routes/+page.svelte | 4 +- web-demo/src/routes/api/+page.svelte | 31 +- web-demo/src/routes/install/+page.svelte | 50 ++-- web-demo/src/routes/integrate/+page.svelte | 11 +- web-demo/static/llms.txt | 21 +- 15 files changed, 689 insertions(+), 430 deletions(-) create mode 100644 src/Helpers/HapticEndpoint.cs delete mode 100644 src/Helpers/HttpsServer.cs create mode 100644 src/Helpers/LocalServer.cs diff --git a/README.md b/README.md index 154faf4..ceabf8d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ -A Logi Actions SDK plugin that exposes MX Master 4 haptic feedback via a local HTTPS server and WebSocket API. +A Logi Actions SDK plugin that exposes MX Master 4 haptic feedback via a local HTTP server and WebSocket API. ## Requirements @@ -18,23 +18,29 @@ A Logi Actions SDK plugin that exposes MX Master 4 haptic feedback via a local H ## API Server -The plugin runs an HTTPS server on `https://local.jmw.nz:41443/` when loaded. +The plugin runs an HTTP server on `http://127.0.0.1:41080/` when loaded. Browsers treat loopback as a secure context, so HTTPS pages can call it directly. -### About local.jmw.nz +### Which websites can use it -`local.jmw.nz` resolves to `127.0.0.1`. The plugin uses this domain to serve HTTPS with a valid SSL certificate instead of self-signed certs that browsers reject. The certificate is automatically downloaded from GitHub, cached locally, and refreshed every 24 hours. +Like phone vibration on the web, any website you visit can trigger haptics and detect that the plugin is running. Chrome asks for your permission before a site can connect to local services. The server only accepts connections from this computer. + +### HTTPS fallback for Safari (deprecated) + +Safari still blocks plain `http://`/`ws://` requests to localhost from HTTPS pages, so the plugin also serves the same API on `https://local.jmw.nz:41443/`. `local.jmw.nz` resolves to `127.0.0.1`, and the certificate is downloaded from GitHub and cached locally; the plugin checks for a new one when it starts (at most once a day). + +This fallback will be removed once Safari allows loopback requests, or by November 2027 at the latest. Try `http://127.0.0.1:41080` first and fall back to it only when that fails (see `web-demo/src/lib/haptics-ws.ts`). ### REST API Endpoints | Endpoint | Method | Description | |----------|--------|-------------| -| `/` | GET | Health check with service info and available endpoints | +| `/` | GET | Health check (`{"success": true, "service": "HapticWebPlugin"}`) | | `/waveforms` | GET | List all 15 available haptic waveforms | | `/haptic/{waveform}` | POST | Trigger a specific haptic waveform | ### WebSocket API -**Endpoint:** `wss://local.jmw.nz:41443/ws` +**Endpoint:** `ws://127.0.0.1:41080/ws` (Safari: `wss://local.jmw.nz:41443/ws`) Keeps a warm connection for theoritically lower latency. @@ -42,6 +48,7 @@ Keeps a warm connection for theoritically lower latency. - Send a single byte containing the waveform index (0-14) - No response is sent back - Connection stays open for repeated triggers +- Messages larger than 1 KB (or frames over 125 bytes) close the connection ### Available Waveforms @@ -71,15 +78,15 @@ The plugin supports 15 haptic waveforms across different categories: ```bash # Health check -curl https://local.jmw.nz:41443/ +curl http://127.0.0.1:41080/ # List all available waveforms -curl https://local.jmw.nz:41443/waveforms +curl http://127.0.0.1:41080/waveforms # Trigger haptic feedback (note: -d '' is required to send Content-Length header) -curl -X POST -d '' https://local.jmw.nz:41443/haptic/sharp_collision -curl -X POST -d '' https://local.jmw.nz:41443/haptic/happy_alert -curl -X POST -d '' https://local.jmw.nz:41443/haptic/completed +curl -X POST -d '' http://127.0.0.1:41080/haptic/sharp_collision +curl -X POST -d '' http://127.0.0.1:41080/haptic/happy_alert +curl -X POST -d '' http://127.0.0.1:41080/haptic/completed # { # "success": true, # "waveform": "completed" @@ -92,8 +99,8 @@ curl -X POST -d '' https://local.jmw.nz:41443/haptic/completed ### WebSocket API (JavaScript) ```javascript -// Connect to WebSocket -const ws = new WebSocket('wss://local.jmw.nz:41443/ws'); +// Connect to WebSocket (Safari: 'wss://local.jmw.nz:41443/ws', deprecated) +const ws = new WebSocket('ws://127.0.0.1:41080/ws'); ws.onopen = () => { console.log('Connected to HapticWeb'); @@ -116,16 +123,16 @@ ws.onerror = (err) => console.error('WebSocket error:', err); ## Technical Details ### Architecture -- **Server:** NetCoreServer-based HTTPS/WSS -- **Port:** 41443 (HTTPS only) -- **Certificate:** Auto-managed from GitHub +- **Server:** NetCoreServer-based HTTP/WS, plus HTTPS/WSS fallback +- **Ports:** 41080 (HTTP), 41443 (HTTPS fallback for Safari, deprecated) - **CORS:** Enabled, any origin - **Binding:** `127.0.0.1` only +- **Limits:** 16 KB per HTTP request, 1 KB per WebSocket message -### Certificate Management +### Certificate Management (HTTPS fallback only) - Downloads from the GitHub `certs` branch on first run - Cached locally in plugin data directory -- Refreshes every 24 hours +- Checks for a new certificate on startup, at most once every 24 hours - Warns 14 days before expiry - Falls back to cache if GitHub is unreachable @@ -140,7 +147,7 @@ Install from the [Logitech Marketplace](https://marketplace.logi.com/plugin/Hapt 3. In the new right sidebar, click the `INSTALL AND UNINSTALL PLUGINS` button. 4. Download the `HapticWeb.lplug4` release asset from [GitHub Releases](https://github.com/fallstop/HapticWebPlugin/releases) and double-click it. 5. This will trigger an installation dialog in Logitech Options+. Press continue. -6. The server starts automatically at `https://local.jmw.nz:41443/` +6. The server starts automatically at `http://127.0.0.1:41080/` 7. Test at [https://haptics.jmw.nz](https://haptics.jmw.nz) ## Development @@ -173,7 +180,7 @@ logiplugintool uninstall HapticWeb ## Troubleshooting -### Certificate Issues +### Certificate Issues (Safari / HTTPS fallback only) If you see certificate errors: 1. Check plugin status in Logi Options+ (should show green "Normal") 2. Verify internet connection (initial certificate download requires network) @@ -181,16 +188,16 @@ If you see certificate errors: 4. Report an issue with the plugin logs if the problem persists ### Port Already in Use -If port 41443 is in use: -1. Stop other services using the port: `lsof -ti:41443 | xargs kill -9` (macOS/Linux) +If port 41080 (or 41443 for the HTTPS fallback) is in use: +1. Stop other services using the port: `lsof -ti:41080 | xargs kill -9` (macOS/Linux) 2. Restart Logi Plugin Service ### WebSocket Connection Failed If WebSocket connections fail: -1. Verify the server is running: `curl https://local.jmw.nz:41443/` +1. Verify the server is running: `curl http://127.0.0.1:41080/` 2. Check browser console for errors -3. Ensure you're using `wss://` (not `ws://`) -4. Verify `local.jmw.nz` resolves to `127.0.0.1`: `ping local.jmw.nz` +3. In Chrome, allow the local network access prompt +4. In Safari, use the HTTPS fallback `wss://local.jmw.nz:41443/ws` and verify `local.jmw.nz` resolves to `127.0.0.1`: `ping local.jmw.nz` ## MIT License diff --git a/src/HapticWebPlugin.cs b/src/HapticWebPlugin.cs index ca25753..643639a 100644 --- a/src/HapticWebPlugin.cs +++ b/src/HapticWebPlugin.cs @@ -17,7 +17,7 @@ public class HapticWebPlugin : Plugin private const Int32 HttpsPort = 41443; private CertificateManager _certificateManager; - private HttpsServer _httpsServer; + private LocalServer _server; private static readonly List HapticWaveforms = new List { @@ -55,7 +55,7 @@ public override void Load() public override void Unload() { - this._httpsServer?.Dispose(); + this._server?.Dispose(); this._certificateManager?.Dispose(); } @@ -63,28 +63,21 @@ private async Task InitializeServerAsync() { try { + this._server = new LocalServer(new HapticEndpoint(this.HandleHttpRequest, this.RunHapticByIndex, HapticWaveforms)); + + // Plain HTTP/WS on loopback needs no certificate, so start it before the download. + this._server.StartHttp(HttpPort); + + // HTTPS is a deprecated fallback for Safari; failures here are warnings only. var pluginDataDir = this.GetPluginDataDirectory(); var certCacheDir = Path.Combine(pluginDataDir, "certificates"); this._certificateManager = new CertificateManager(certCacheDir); await this._certificateManager.InitializeAsync(); - this.UpdatePluginStatus(); - - this._httpsServer = new HttpsServer( - HttpPort, - HttpsPort, - this._certificateManager.Certificate, - this.HandleHttpRequest, - this.RunHapticByIndex, - HapticWaveforms); - - this._httpsServer.Start(); + this._server.StartHttps(HttpsPort, this._certificateManager.Certificate); - if (!String.IsNullOrEmpty(this._httpsServer.BindError)) - { - this.OnPluginStatusChanged(Loupedeck.PluginStatus.Error, this._httpsServer.BindError); - } + this.UpdatePluginStatus(); } catch (Exception ex) { @@ -95,35 +88,30 @@ private async Task InitializeServerAsync() private void UpdatePluginStatus() { - switch (this._certificateManager.Status) - { - case CertificateStatus.Error: - this.OnPluginStatusChanged(Loupedeck.PluginStatus.Error, this._certificateManager.StatusMessage); - break; - - case CertificateStatus.Expired: - this.OnPluginStatusChanged( - Loupedeck.PluginStatus.Warning, - this._certificateManager.StatusMessage, - "https://github.com/fallstop/HapticWebPlugin/issues", - "Report Issue"); - break; - - case CertificateStatus.ExpiringSoon: - this.OnPluginStatusChanged( - Loupedeck.PluginStatus.Warning, - this._certificateManager.StatusMessage, - null, - null); - break; - - case CertificateStatus.Valid: - this.OnPluginStatusChanged(Loupedeck.PluginStatus.Normal, null); - break; - - default: - break; + if (this._server.HttpError != null) + { + this.OnPluginStatusChanged(Loupedeck.PluginStatus.Error, this._server.HttpError); + return; } + + var httpsProblem = this._certificateManager.Status switch + { + CertificateStatus.Valid => this._server.HttpsError, + CertificateStatus.NotLoaded => this._server.HttpsError, + _ => this._certificateManager.StatusMessage ?? this._server.HttpsError, + }; + + if (httpsProblem != null) + { + this.OnPluginStatusChanged( + Loupedeck.PluginStatus.Warning, + $"HTTPS fallback (used by Safari) is unavailable: {httpsProblem}", + "https://github.com/fallstop/HapticWebPlugin/issues", + "Report Issue"); + return; + } + + this.OnPluginStatusChanged(Loupedeck.PluginStatus.Normal, null); } private Task HandleHttpRequest(String method, String path) @@ -152,14 +140,7 @@ private Object HandleHealthCheck() return new { success = true, - service = "HapticWebPlugin", - version = "1.0.0", - endpoints = new - { - health = "GET /", - listWaveforms = "GET /waveforms", - triggerHaptic = "POST /haptic/{waveform}" - } + service = "HapticWebPlugin" }; } diff --git a/src/Helpers/HapticEndpoint.cs b/src/Helpers/HapticEndpoint.cs new file mode 100644 index 0000000..8f28b03 --- /dev/null +++ b/src/Helpers/HapticEndpoint.cs @@ -0,0 +1,205 @@ +namespace Loupedeck.HapticWebPlugin.Helpers +{ + using System; + using System.Collections.Generic; + using System.Text; + using System.Text.Json; + + using NetCoreServer; + + /// + /// Request handling shared by the HTTP (ws://) and HTTPS (wss://) listeners. + /// + internal sealed class HapticEndpoint + { + private readonly Func> _requestHandler; + private readonly Action _runHapticByIndex; + private readonly IReadOnlyList _waveforms; + + public HapticEndpoint( + Func> requestHandler, + Action runHapticByIndex, + IReadOnlyList waveforms) + { + this._requestHandler = requestHandler; + this._runHapticByIndex = runHapticByIndex; + this._waveforms = waveforms; + } + + // Only /ws upgrades; anything else is answered as a normal HTTP request. + public static Boolean IsWebSocketPath(HttpRequest request) => request.Url == "/ws"; + + public void HandleWebSocketMessage(Byte[] buffer, Int64 offset, Int64 size) + { + if (size < 1) + { + return; + } + + var index = (Int32)buffer[offset]; + + if (index < this._waveforms.Count) + { + this._runHapticByIndex(index); + PluginLog.Verbose($"WebSocket haptic triggered: index={index}, waveform={this._waveforms[index]}"); + } + else + { + PluginLog.Warning($"WebSocket received invalid haptic index: {index}"); + } + } + + public void HandleHttpRequest(HttpRequest request, Func send) + { + var method = request.Method; + var path = request.Url; + + PluginLog.Verbose($"HTTP {method} {path}"); + + if (method == "OPTIONS") + { + send(CorsPreflightResponse()); + return; + } + + System.Threading.Tasks.Task.Run(async () => + { + try + { + var result = await this._requestHandler(method, path); + + send(result == null + ? JsonResponse(404, new { success = false, error = "Not found" }) + : JsonResponse(200, result)); + } + catch (Exception ex) + { + PluginLog.Error(ex, "Request handler error"); + send(JsonResponse(500, new { success = false, error = "Internal error" })); + } + }); + } + + private static HttpResponse CorsPreflightResponse() + { + var response = new HttpResponse(); + response.SetBegin(200); + response.SetHeader("Access-Control-Allow-Origin", "*"); + response.SetHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + response.SetHeader("Access-Control-Allow-Headers", "Content-Type"); + response.SetHeader("Access-Control-Allow-Private-Network", "true"); + response.SetHeader("Access-Control-Max-Age", "86400"); + response.SetBody(); + return response; + } + + private static HttpResponse JsonResponse(Int32 statusCode, Object data) + { + var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true })); + + var response = new HttpResponse(); + response.SetBegin(statusCode); + response.SetHeader("Content-Type", "application/json; charset=utf-8"); + response.SetHeader("Access-Control-Allow-Origin", "*"); + response.SetHeader("Access-Control-Allow-Private-Network", "true"); + response.SetBody(body); + return response; + } + } + + /// + /// Rejects oversized input before NetCoreServer buffers it. NetCoreServer has no + /// request or WebSocket message size limit of its own and buffers a whole frame + /// (whatever length the client declares) before handing it to us. + /// Every haptic command is a single byte, so the limits are tiny. + /// + internal sealed class ReceiveGuard + { + // Largest payload that fits the 7-bit length field; frames needing an + // extended length are never valid for this protocol. + public const Int32 MaxFramePayload = 125; + public const Int32 MaxMessageBytes = 1024; + public const Int32 MaxHttpRequestBytes = 16 * 1024; + + private readonly Byte[] _header = new Byte[6]; + private Int32 _headerLength; + private Int64 _payloadRemaining; + private Int64 _messageLength; + private Int64 _httpBytes; + + public Boolean IsWebSocket { get; private set; } + + public void EnterWebSocketMode() + { + this.IsWebSocket = true; + this._httpBytes = 0; + } + + public void HttpRequestCompleted() => this._httpBytes = 0; + + /// false if the connection should be dropped. + public Boolean Accept(Byte[] buffer, Int64 offset, Int64 size) + { + if (!this.IsWebSocket) + { + this._httpBytes += size; + return this._httpBytes <= MaxHttpRequestBytes; + } + + var end = offset + size; + var i = offset; + while (i < end) + { + if (this._payloadRemaining > 0) + { + var skip = Math.Min(this._payloadRemaining, end - i); + i += skip; + this._payloadRemaining -= skip; + continue; + } + + this._header[this._headerLength++] = buffer[i++]; + if (this._headerLength < 2) + { + continue; + } + + var payloadLength = this._header[1] & 0x7F; + if (payloadLength > MaxFramePayload) + { + return false; + } + + var masked = (this._header[1] & 0x80) != 0; + if (this._headerLength < (masked ? 6 : 2)) + { + continue; + } + + var opcode = this._header[0] & 0x0F; + var fin = (this._header[0] & 0x80) != 0; + + // Data and continuation frames build up one message; control frames + // (opcode >= 8) can interleave and are capped at 125 bytes by the RFC. + if (opcode < 0x8) + { + this._messageLength += payloadLength; + if (this._messageLength > MaxMessageBytes) + { + return false; + } + + if (fin) + { + this._messageLength = 0; + } + } + + this._payloadRemaining = payloadLength; + this._headerLength = 0; + } + + return true; + } + } +} diff --git a/src/Helpers/HttpsServer.cs b/src/Helpers/HttpsServer.cs deleted file mode 100644 index f51dd3e..0000000 --- a/src/Helpers/HttpsServer.cs +++ /dev/null @@ -1,275 +0,0 @@ -namespace Loupedeck.HapticWebPlugin.Helpers -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Sockets; - using System.Security.Cryptography.X509Certificates; - using System.Text; - using System.Text.Json; - - using NetCoreServer; - - public class HttpsServer : IDisposable - { - private readonly Int32 _httpsPort; - private readonly X509Certificate2 _certificate; - private readonly Func> _requestHandler; - private readonly Action _runHapticByIndex; - private readonly IReadOnlyList _waveforms; - - private HapticWssServer _server; - private Boolean _isRunning; - private String _bindError; - - public Boolean IsRunning => this._isRunning; - public String BindError => this._bindError; - - public HttpsServer( - Int32 httpPort, // Ignored - HTTPS only - Int32 httpsPort, - X509Certificate2 certificate, - Func> requestHandler, - Action runHapticByIndex, - IReadOnlyList waveforms) - { - this._httpsPort = httpsPort; - this._certificate = certificate; - this._requestHandler = requestHandler; - this._runHapticByIndex = runHapticByIndex; - this._waveforms = waveforms; - } - - public void Start() - { - if (this._isRunning) - { - return; - } - - if (this._certificate == null) - { - this._bindError = "Server can't start without SSL certificate"; - PluginLog.Error(this._bindError); - return; - } - - try - { - var context = new SslContext(System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13, this._certificate); - - this._server = new HapticWssServer( - context, - IPAddress.Loopback, - this._httpsPort, - this._requestHandler, - this._runHapticByIndex, - this._waveforms); - - if (!this._server.Start()) - { - this._bindError = $"Failed to start server on port {this._httpsPort}"; - PluginLog.Error(this._bindError); - return; - } - - this._isRunning = true; - PluginLog.Info($"HTTPS/WSS server started on https://local.jmw.nz:{this._httpsPort}/"); - } - catch (SocketException ex) when ( - ex.SocketErrorCode == SocketError.AddressAlreadyInUse || - ex.SocketErrorCode == SocketError.AccessDenied) - { - this._bindError = $"Port {this._httpsPort} is already in use. Close any other apps using this port."; - PluginLog.Error(ex, this._bindError); - } - catch (Exception ex) - { - this._bindError = $"Failed to start server: {ex.Message}"; - PluginLog.Error(ex, "Server startup error"); - } - } - - public void Stop() - { - if (!this._isRunning) - { - return; - } - - this._server?.Stop(); - this._isRunning = false; - PluginLog.Info("HTTPS/WSS server stopped"); - } - - public void Dispose() - { - this.Stop(); - this._server?.Dispose(); - } - } - - internal class HapticWssServer : WssServer - { - private readonly Func> _requestHandler; - private readonly Action _runHapticByIndex; - private readonly IReadOnlyList _waveforms; - - public HapticWssServer( - SslContext context, - IPAddress address, - Int32 port, - Func> requestHandler, - Action runHapticByIndex, - IReadOnlyList waveforms) - : base(context, address, port) - { - this._requestHandler = requestHandler; - this._runHapticByIndex = runHapticByIndex; - this._waveforms = waveforms; - - // Disable WebSocket compression to avoid RSV1 bit issues - this.OptionNoDelay = true; - } - - protected override SslSession CreateSession() - { - return new HapticWssSession(this, this._requestHandler, this._runHapticByIndex, this._waveforms); - } - - protected override void OnError(SocketError error) - { - PluginLog.Error($"WSS server error: {error}"); - } - } - - internal class HapticWssSession : WssSession - { - private readonly Func> _requestHandler; - private readonly Action _runHapticByIndex; - private readonly IReadOnlyList _waveforms; - - public HapticWssSession( - WssServer server, - Func> requestHandler, - Action runHapticByIndex, - IReadOnlyList waveforms) - : base(server) - { - this._requestHandler = requestHandler; - this._runHapticByIndex = runHapticByIndex; - this._waveforms = waveforms; - } - - public override void OnWsConnected(HttpRequest request) - { - PluginLog.Info($"WebSocket connected: {Id}"); - } - - public override void OnWsDisconnected() - { - PluginLog.Verbose($"WebSocket disconnected: {Id}"); - } - - public override void OnWsReceived(Byte[] buffer, Int64 offset, Int64 size) - { - if (size >= 1) - { - var index = (Int32)buffer[offset]; - - if (index >= 0 && index < this._waveforms.Count) - { - this._runHapticByIndex(index); - PluginLog.Verbose($"WebSocket haptic triggered: index={index}, waveform={this._waveforms[index]}"); - } - else - { - PluginLog.Warning($"WebSocket received invalid haptic index: {index}"); - } - } - } - - protected override void OnReceivedRequest(HttpRequest request) - { - var method = request.Method; - var path = request.Url; - - // Let base class handle WebSocket upgrade requests - // WebSocket upgrades come as GET with Upgrade: websocket header - // After upgrade, OnReceivedRequest shouldn't be called for WS frames - // but if it is, checking for path helps avoid breaking things - if (method == "GET" && path == "/ws") - { - // This was a WebSocket upgrade - base class handles it via OnReceivedRequestHeader - // Just return and let WssSession handle WebSocket frames - return; - } - - PluginLog.Verbose($"HTTPS {method} {path}"); - - // Handle CORS preflight - if (method == "OPTIONS") - { - this.SendCorsPreflightResponse(); - return; - } - - // Handle HTTP requests (not WebSocket) - System.Threading.Tasks.Task.Run(async () => - { - try - { - var result = await this._requestHandler(method, path); - - if (result == null) - { - this.SendJsonResponse(404, new { success = false, error = "Not found" }); - return; - } - - this.SendJsonResponse(200, result); - } - catch (Exception ex) - { - PluginLog.Error(ex, "Request handler error"); - this.SendJsonResponse(500, new { success = false, error = ex.Message }); - } - }); - } - - private void SendCorsPreflightResponse() - { - var response = new HttpResponse(); - response.SetBegin(200); - response.SetHeader("Access-Control-Allow-Origin", "*"); - response.SetHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); - response.SetHeader("Access-Control-Allow-Headers", "Content-Type"); - response.SetHeader("Access-Control-Allow-Private-Network", "true"); - response.SetHeader("Access-Control-Max-Age", "86400"); - response.SetBody(); - this.SendResponseAsync(response); - } - - private void SendJsonResponse(Int32 statusCode, Object data) - { - var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }); - var body = Encoding.UTF8.GetBytes(json); - - var response = new HttpResponse(); - response.SetBegin(statusCode); - response.SetHeader("Content-Type", "application/json; charset=utf-8"); - response.SetHeader("Access-Control-Allow-Origin", "*"); - response.SetHeader("Access-Control-Allow-Private-Network", "true"); - response.SetBody(body); - this.SendResponseAsync(response); - } - - protected override void OnError(SocketError error) - { - if (error != SocketError.ConnectionReset) - { - PluginLog.Warning($"WSS session error: {error}"); - } - } - } -} diff --git a/src/Helpers/LocalServer.cs b/src/Helpers/LocalServer.cs new file mode 100644 index 0000000..6cec6bf --- /dev/null +++ b/src/Helpers/LocalServer.cs @@ -0,0 +1,256 @@ +namespace Loupedeck.HapticWebPlugin.Helpers +{ + using System; + using System.Net; + using System.Net.Sockets; + using System.Security.Cryptography.X509Certificates; + + using NetCoreServer; + + /// + /// Runs the loopback listeners: + /// - HTTP/WS on 127.0.0.1 (primary; loopback is a secure context, so HTTPS pages can use it) + /// - HTTPS/WSS on local.jmw.nz (deprecated fallback for Safari, which still blocks + /// ws:// to loopback from HTTPS pages) + /// + internal sealed class LocalServer : IDisposable + { + private readonly HapticEndpoint _endpoint; + + private HapticWsServer _httpServer; + private HapticWssServer _httpsServer; + + public String HttpError { get; private set; } + public String HttpsError { get; private set; } + + public LocalServer(HapticEndpoint endpoint) + { + this._endpoint = endpoint; + } + + public void StartHttp(Int32 port) + { + var server = new HapticWsServer(IPAddress.Loopback, port, this._endpoint); + this.HttpError = TryStart(server.Start, port, $"HTTP/WS server started on http://127.0.0.1:{port}/"); + if (this.HttpError == null) + { + this._httpServer = server; + } + else + { + server.Dispose(); + } + } + + public void StartHttps(Int32 port, X509Certificate2 certificate) + { + if (certificate == null) + { + this.HttpsError = "Server can't start without SSL certificate"; + PluginLog.Error(this.HttpsError); + return; + } + + var context = new SslContext(System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13, certificate); + var server = new HapticWssServer(context, IPAddress.Loopback, port, this._endpoint); + this.HttpsError = TryStart(server.Start, port, $"HTTPS/WSS server started on https://local.jmw.nz:{port}/"); + if (this.HttpsError == null) + { + this._httpsServer = server; + } + else + { + server.Dispose(); + } + } + + private static String TryStart(Func start, Int32 port, String startedMessage) + { + try + { + if (!start()) + { + var error = $"Failed to start server on port {port}"; + PluginLog.Error(error); + return error; + } + + PluginLog.Info(startedMessage); + return null; + } + catch (SocketException ex) when ( + ex.SocketErrorCode == SocketError.AddressAlreadyInUse || + ex.SocketErrorCode == SocketError.AccessDenied) + { + var error = $"Port {port} is already in use. Close any other apps using this port."; + PluginLog.Error(ex, error); + return error; + } + catch (Exception ex) + { + PluginLog.Error(ex, "Server startup error"); + return $"Failed to start server: {ex.Message}"; + } + } + + public void Dispose() + { + this._httpServer?.Stop(); + this._httpServer?.Dispose(); + this._httpServer = null; + + this._httpsServer?.Stop(); + this._httpsServer?.Dispose(); + this._httpsServer = null; + } + } + + internal sealed class HapticWsServer : WsServer + { + private readonly HapticEndpoint _endpoint; + + public HapticWsServer(IPAddress address, Int32 port, HapticEndpoint endpoint) + : base(address, port) + { + this._endpoint = endpoint; + this.OptionNoDelay = true; + } + + protected override TcpSession CreateSession() => new HapticWsSession(this, this._endpoint); + + protected override void OnError(SocketError error) => PluginLog.Error($"WS server error: {error}"); + } + + internal sealed class HapticWssServer : WssServer + { + private readonly HapticEndpoint _endpoint; + + public HapticWssServer(SslContext context, IPAddress address, Int32 port, HapticEndpoint endpoint) + : base(context, address, port) + { + this._endpoint = endpoint; + this.OptionNoDelay = true; + } + + protected override SslSession CreateSession() => new HapticWssSession(this, this._endpoint); + + protected override void OnError(SocketError error) => PluginLog.Error($"WSS server error: {error}"); + } + + // The two session classes are identical apart from their base class (NetCoreServer + // has separate plain and TLS hierarchies); all logic lives in HapticEndpoint/ReceiveGuard. + + internal sealed class HapticWsSession : WsSession + { + private readonly HapticEndpoint _endpoint; + private readonly ReceiveGuard _guard = new ReceiveGuard(); + + public HapticWsSession(WsServer server, HapticEndpoint endpoint) + : base(server) + { + this._endpoint = endpoint; + } + + protected override void OnReceived(Byte[] buffer, Int64 offset, Int64 size) + { + if (!this._guard.Accept(buffer, offset, size)) + { + PluginLog.Warning($"Dropping connection {this.Id}: request or message too large"); + this.Disconnect(); + return; + } + + base.OnReceived(buffer, offset, size); + } + + public override Boolean OnWsConnecting(HttpRequest request, HttpResponse response) => HapticEndpoint.IsWebSocketPath(request); + + public override void OnWsConnected(HttpRequest request) + { + this._guard.EnterWebSocketMode(); + PluginLog.Info($"WebSocket connected: {this.Id}"); + } + + public override void OnWsDisconnected() => PluginLog.Verbose($"WebSocket disconnected: {this.Id}"); + + public override void OnWsReceived(Byte[] buffer, Int64 offset, Int64 size) => this._endpoint.HandleWebSocketMessage(buffer, offset, size); + + protected override void OnReceivedRequest(HttpRequest request) + { + if (this._guard.IsWebSocket) + { + // The upgrade request itself; the base class handles any frame bytes sent with it. + base.OnReceivedRequest(request); + return; + } + + this._guard.HttpRequestCompleted(); + this._endpoint.HandleHttpRequest(request, this.SendResponseAsync); + } + + protected override void OnError(SocketError error) + { + if (error != SocketError.ConnectionReset) + { + PluginLog.Warning($"WS session error: {error}"); + } + } + } + + internal sealed class HapticWssSession : WssSession + { + private readonly HapticEndpoint _endpoint; + private readonly ReceiveGuard _guard = new ReceiveGuard(); + + public HapticWssSession(WssServer server, HapticEndpoint endpoint) + : base(server) + { + this._endpoint = endpoint; + } + + protected override void OnReceived(Byte[] buffer, Int64 offset, Int64 size) + { + if (!this._guard.Accept(buffer, offset, size)) + { + PluginLog.Warning($"Dropping connection {this.Id}: request or message too large"); + this.Disconnect(); + return; + } + + base.OnReceived(buffer, offset, size); + } + + public override Boolean OnWsConnecting(HttpRequest request, HttpResponse response) => HapticEndpoint.IsWebSocketPath(request); + + public override void OnWsConnected(HttpRequest request) + { + this._guard.EnterWebSocketMode(); + PluginLog.Info($"WebSocket connected: {this.Id}"); + } + + public override void OnWsDisconnected() => PluginLog.Verbose($"WebSocket disconnected: {this.Id}"); + + public override void OnWsReceived(Byte[] buffer, Int64 offset, Int64 size) => this._endpoint.HandleWebSocketMessage(buffer, offset, size); + + protected override void OnReceivedRequest(HttpRequest request) + { + if (this._guard.IsWebSocket) + { + // The upgrade request itself; the base class handles any frame bytes sent with it. + base.OnReceivedRequest(request); + return; + } + + this._guard.HttpRequestCompleted(); + this._endpoint.HandleHttpRequest(request, this.SendResponseAsync); + } + + protected override void OnError(SocketError error) + { + if (error != SocketError.ConnectionReset) + { + PluginLog.Warning($"WSS session error: {error}"); + } + } + } +} diff --git a/src/package/metadata/LoupedeckPackage.yaml b/src/package/metadata/LoupedeckPackage.yaml index 378c59b..61769a9 100644 --- a/src/package/metadata/LoupedeckPackage.yaml +++ b/src/package/metadata/LoupedeckPackage.yaml @@ -12,13 +12,13 @@ name: HapticWeb displayName: Haptic Web Plugin # Short description of the plugin. -description: Exposes MX Master 4 haptic feedback via a local HTTPS server and WebSocket API for web applications. +description: Exposes MX Master 4 haptic feedback via a local HTTP server and WebSocket API for web applications. Like phone vibration on the web, any website you visit can trigger haptics and detect that the plugin is running; Chrome asks for permission first. # Name of the plugin library file. pluginFileName: HapticWebPlugin.dll # Plugin version. -version: 1.2 +version: 1.3 # Author of the plugin. The author can be a company or an individual developer. author: Jasper M-W diff --git a/web-demo/src/lib/components/ApiReference.svelte b/web-demo/src/lib/components/ApiReference.svelte index 54e8d0b..cc9e6e6 100644 --- a/web-demo/src/lib/components/ApiReference.svelte +++ b/web-demo/src/lib/components/ApiReference.svelte @@ -36,9 +36,7 @@ curl: `curl ${API_BASE}/`, response: `{ "success": true, - "service": "HapticWebPlugin", - "version": "1.0.0", - "endpoints": { ... } + "service": "HapticWebPlugin" }`, }, { @@ -98,7 +96,7 @@ REST API endpoints for integrating haptic feedback. The WebSocket endpoint wss://{API_HOST}:{API_PORT}/ws + >ws://{API_HOST}:{API_PORT}/ws provides lower latency for real-time triggering. diff --git a/web-demo/src/lib/config.ts b/web-demo/src/lib/config.ts index 7b1add2..6e6cbf4 100644 --- a/web-demo/src/lib/config.ts +++ b/web-demo/src/lib/config.ts @@ -1,3 +1,19 @@ -export const API_HOST = 'local.jmw.nz'; -export const API_PORT = 41443; -export const API_BASE_URL = `https://${API_HOST}:${API_PORT}`; +/** + * Primary endpoint: plain HTTP/WS on loopback. Browsers treat 127.0.0.1 as a + * secure context, so HTTPS pages can call it without mixed-content errors. + */ +export const API_HOST = '127.0.0.1'; +export const API_PORT = 41080; +export const API_BASE_URL = `http://${API_HOST}:${API_PORT}`; + +/** + * Deprecated HTTPS fallback for Safari, which still blocks http/ws requests to + * loopback from HTTPS pages. Will be removed once Safari allows them, or by + * November 2027 at the latest. + */ +export const FALLBACK_API_HOST = 'local.jmw.nz'; +export const FALLBACK_API_PORT = 41443; +export const FALLBACK_API_BASE_URL = `https://${FALLBACK_API_HOST}:${FALLBACK_API_PORT}`; + +/** Endpoints to try, in order. */ +export const API_BASE_URLS = [API_BASE_URL, FALLBACK_API_BASE_URL]; diff --git a/web-demo/src/lib/haptics-ws.ts b/web-demo/src/lib/haptics-ws.ts index 25cbe43..ba0239e 100644 --- a/web-demo/src/lib/haptics-ws.ts +++ b/web-demo/src/lib/haptics-ws.ts @@ -5,10 +5,11 @@ * - Auto-reconnect with exponential backoff (capped at 15s) * - Pre-allocated buffer for zero-allocation sends * - Service validation to detect wrong service on port + * - Tries plain ws://127.0.0.1 first, then the HTTPS fallback (for Safari) * - Graceful error handling for connection refused, timeout, wrong service */ -import { API_BASE_URL } from './config'; +import { API_BASE_URLS } from './config'; export type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting'; @@ -21,8 +22,11 @@ export type ErrorType = | 'ssl_error'; // Certificate issue export interface HapticsWebSocketOptions { - /** Base URL for the haptics service (default: 'https://local.jmw.nz:41443') */ - baseUrl?: string; + /** + * Base URLs for the haptics service, tried in order + * (default: ['http://127.0.0.1:41080', 'https://local.jmw.nz:41443']) + */ + baseUrls?: string[]; /** Initial reconnect delay in ms (default: 1000) */ initialReconnectDelay?: number; /** Maximum reconnect delay in ms (default: 15000) */ @@ -40,7 +44,7 @@ export interface HapticsWebSocketState { } const DEFAULT_OPTIONS: Required> = { - baseUrl: API_BASE_URL, + baseUrls: API_BASE_URLS, initialReconnectDelay: 1000, maxReconnectDelay: 15000, connectionTimeout: 5000, @@ -121,8 +125,8 @@ export class HapticsWebSocket { null ); - // First, validate the service is correct by checking the health endpoint - const validation = await this.validateService(); + // First, find an endpoint that answers as the haptics service + const validation = await this.findService(); if (!validation.valid) { this.updateState('disconnected', validation.errorType, validation.errorMessage); this.scheduleReconnect(); @@ -130,7 +134,7 @@ export class HapticsWebSocket { } // Now attempt WebSocket connection - const wsUrl = this.options.baseUrl.replace(/^http/, 'ws') + '/ws'; + const wsUrl = validation.baseUrl.replace(/^http/, 'ws') + '/ws'; try { this.ws = new WebSocket(wsUrl); @@ -171,12 +175,32 @@ export class HapticsWebSocket { } } - private async validateService(): Promise<{ valid: boolean; errorType: ErrorType; errorMessage: string | null }> { + /** + * Try each base URL in order and return the first that answers as the haptics service. + * If none do, report the most specific error (anything over "connection refused"). + */ + private async findService(): Promise<{ valid: true; baseUrl: string } | { valid: false; errorType: ErrorType; errorMessage: string | null }> { + let failure: { valid: false; errorType: ErrorType; errorMessage: string | null } | null = null; + + for (const baseUrl of this.options.baseUrls) { + const result = await this.validateService(baseUrl); + if (result.valid) { + return { valid: true, baseUrl }; + } + if (!failure || failure.errorType === 'connection_refused') { + failure = result; + } + } + + return failure ?? { valid: false, errorType: 'connection_refused', errorMessage: 'Cannot connect to haptics service' }; + } + + private async validateService(baseUrl: string): Promise<{ valid: false; errorType: ErrorType; errorMessage: string | null } | { valid: true }> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.options.connectionTimeout); try { - const response = await fetch(this.options.baseUrl + '/', { + const response = await fetch(baseUrl + '/', { method: 'GET', signal: controller.signal, }); @@ -197,7 +221,7 @@ export class HapticsWebSocket { }; } - return { valid: true, errorType: 'none', errorMessage: null }; + return { valid: true }; } catch (error) { clearTimeout(timeoutId); diff --git a/web-demo/src/lib/haptics.ts b/web-demo/src/lib/haptics.ts index 8a75f2c..7792da2 100644 --- a/web-demo/src/lib/haptics.ts +++ b/web-demo/src/lib/haptics.ts @@ -1,6 +1,4 @@ -import { API_BASE_URL } from './config'; - -const API_BASE = API_BASE_URL; +import { API_BASE_URLS } from './config'; import waveformsData from '$lib/data/waveforms.json'; @@ -41,9 +39,40 @@ export interface HapticResponse { waveform: string; } +// Base URL that last answered as the haptics service (plain HTTP first, HTTPS fallback for Safari) +let resolvedApiBase: Promise | null = null; + +async function findApiBase(): Promise { + for (const baseUrl of API_BASE_URLS) { + try { + const response = await fetch(baseUrl + '/', { method: 'GET' }); + if (response.ok && (await response.json())?.service === 'HapticWebPlugin') { + return baseUrl; + } + } catch { + // Not reachable from this page (not running, or blocked as mixed content); try the next one + } + } + return null; +} + +function getApiBase(): Promise { + resolvedApiBase ??= findApiBase().then((base) => { + if (base === null) resolvedApiBase = null; // retry on the next call + return base; + }); + return resolvedApiBase; +} + export async function triggerWaveform(waveformApiName: string): Promise { + const apiBase = await getApiBase(); + if (apiBase === null) { + console.error('Failed to trigger waveform: haptics service not reachable'); + return null; + } + try { - const response = await fetch(`${API_BASE}/haptic/${waveformApiName}`, { + const response = await fetch(`${apiBase}/haptic/${waveformApiName}`, { method: 'POST', }); if (!response.ok) { @@ -52,18 +81,15 @@ export async function triggerWaveform(waveformApiName: string): Promise { - try { - const response = await fetch(API_BASE, { method: 'GET' }); - return response.ok; - } catch { - return false; - } + resolvedApiBase = null; + return (await getApiBase()) !== null; } // Convert waveform encoding to chart-friendly data diff --git a/web-demo/src/routes/+page.svelte b/web-demo/src/routes/+page.svelte index 4da860d..1b1c9db 100644 --- a/web-demo/src/routes/+page.svelte +++ b/web-demo/src/routes/+page.svelte @@ -44,7 +44,7 @@ HapticWeb — MX Master 4 Haptic Feedback API + content="A Logi Actions SDK plugin that exposes MX Master 4 haptic feedback via a local HTTP server and WebSocket API." /> @@ -82,7 +82,7 @@

A plugin that exposes MX Master 4 haptic feedback through a local - HTTPS server and WebSocket API. Add tactile feedback to your web apps, + HTTP server and WebSocket API. Add tactile feedback to your web apps, games, and creative tools.

diff --git a/web-demo/src/routes/api/+page.svelte b/web-demo/src/routes/api/+page.svelte index b2a6d83..b7cccb1 100644 --- a/web-demo/src/routes/api/+page.svelte +++ b/web-demo/src/routes/api/+page.svelte @@ -1,7 +1,7 @@