diff --git a/README.md b/README.md index 154faf4..7379223 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. Chrome and Firefox treat loopback as a secure context, so HTTPS pages can call it directly (Safari: see the HTTPS fallback below). -### 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 use `https://local.jmw.nz:41443` 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 that port, e.g. `lsof -ti:41080 | xargs kill -9` (macOS/Linux; use 41443 for the fallback) 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 it is running: `curl https://local.jmw.nz:41443/` (if that fails, check the plugin status in Logi Options+ and that `local.jmw.nz` resolves to `127.0.0.1`) ## MIT License diff --git a/src/HapticWebPlugin.cs b/src/HapticWebPlugin.cs index ca25753..3871e1b 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,27 +63,23 @@ 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._server.StartHttps(HttpsPort, this._certificateManager.Certificate); - this._httpsServer.Start(); - - if (!String.IsNullOrEmpty(this._httpsServer.BindError)) + if (!this._server.IsDisposed) { - this.OnPluginStatusChanged(Loupedeck.PluginStatus.Error, this._httpsServer.BindError); + this.UpdatePluginStatus(); } } catch (Exception ex) @@ -95,35 +91,36 @@ 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 or CertificateStatus.NotLoaded or CertificateStatus.ExpiringSoon => this._server.HttpsError, + _ => this._certificateManager.StatusMessage ?? this._server.HttpsError, + }; + + if (httpsProblem == null && this._certificateManager.Status == CertificateStatus.ExpiringSoon) + { + // Still serving; just flag that renewal hasn't happened yet. + this.OnPluginStatusChanged(Loupedeck.PluginStatus.Warning, this._certificateManager.StatusMessage, null, null); + return; + } + + 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 +149,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..d816a57 --- /dev/null +++ b/src/Helpers/HapticEndpoint.cs @@ -0,0 +1,231 @@ +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. + /// + /// In WebSocket mode it also holds back a frame header that is split across reads + /// and forwards it whole with the next read: NetCoreServer 8.0.7 restarts its header + /// loops from zero on a split header and would misparse the stream, which would also + /// put it out of step with this guard. + /// + 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; + + /// + /// Checks received bytes and rewrites the range to forward to NetCoreServer + /// (which may be empty, or include header bytes held back from the previous read). + /// + /// false if the connection should be dropped. + public Boolean Filter(ref Byte[] buffer, ref Int64 offset, ref Int64 size) + { + if (!this.IsWebSocket) + { + this._httpBytes += size; + return this._httpBytes <= MaxHttpRequestBytes; + } + + if (this._headerLength > 0) + { + var combined = new Byte[this._headerLength + size]; + Array.Copy(this._header, combined, this._headerLength); + Array.Copy(buffer, offset, combined, this._headerLength, size); + buffer = combined; + offset = 0; + size = combined.Length; + this._headerLength = 0; + } + + var end = offset + size; + var i = offset; + var frameStart = offset; + while (i < end) + { + if (this._payloadRemaining > 0) + { + var skip = Math.Min(this._payloadRemaining, end - i); + i += skip; + this._payloadRemaining -= skip; + continue; + } + + if (this._headerLength == 0) + { + frameStart = i; + } + + 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; + } + + // NetCoreServer appends every frame's payload (control frames included) + // to one message buffer until a frame with FIN set, so count them all. + this._messageLength += payloadLength; + if (this._messageLength > MaxMessageBytes) + { + return false; + } + + if ((this._header[0] & 0x80) != 0) + { + this._messageLength = 0; + } + + this._payloadRemaining = payloadLength; + this._headerLength = 0; + } + + if (this._headerLength > 0) + { + // Hold the partial header back; it is prepended to the next read. + size = frameStart - offset; + } + + 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..83df50f --- /dev/null +++ b/src/Helpers/LocalServer.cs @@ -0,0 +1,297 @@ +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 readonly Object _lock = new Object(); + private HapticWsServer _httpServer; + private HapticWssServer _httpsServer; + private Boolean _disposed; + + public String HttpError { get; private set; } + public String HttpsError { get; private set; } + + public LocalServer(HapticEndpoint endpoint) + { + this._endpoint = endpoint; + } + + public void StartHttp(Int32 port) + { + lock (this._lock) + { + if (this._disposed) + { + return; + } + + 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; + } + + lock (this._lock) + { + // The certificate download can finish after the plugin has unloaded. + if (this._disposed) + { + 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 Boolean IsDisposed + { + get + { + lock (this._lock) + { + return this._disposed; + } + } + } + + public void Dispose() + { + lock (this._lock) + { + this._disposed = true; + + 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.Filter(ref buffer, ref offset, ref size)) + { + PluginLog.Warning($"Dropping connection {this.Id}: request or message too large"); + this.Disconnect(); + return; + } + + if (size > 0) + { + 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 would feed any request body to the + // frame parser without passing through ReceiveGuard; browsers never send one. + 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.Filter(ref buffer, ref offset, ref size)) + { + PluginLog.Warning($"Dropping connection {this.Id}: request or message too large"); + this.Disconnect(); + return; + } + + if (size > 0) + { + 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 would feed any request body to the + // frame parser without passing through ReceiveGuard; browsers never send one. + 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/components/StatusBanner.svelte b/web-demo/src/lib/components/StatusBanner.svelte index dca3af0..83c2975 100644 --- a/web-demo/src/lib/components/StatusBanner.svelte +++ b/web-demo/src/lib/components/StatusBanner.svelte @@ -77,10 +77,10 @@ case "ssl_error": return { icon: ShieldAlert, - title: "SSL Certificate Error", + title: "Connection Error", description: errorMessage || - "Trust the local.jmw.nz certificate in your browser", + "Couldn't connect to the haptics service. Restart Logi Plugin Service and try again.", borderClass: "border-orange-500/30", bgClass: "bg-orange-500/10", titleClass: "text-orange-400", diff --git a/web-demo/src/lib/config.ts b/web-demo/src/lib/config.ts index 7b1add2..ebdfab9 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. Chrome and Firefox 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..1baf893 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'; @@ -20,9 +21,14 @@ export type ErrorType = | 'websocket_error' // Generic WebSocket error | 'ssl_error'; // Certificate issue +type ServiceFailure = { valid: false; errorType: ErrorType; errorMessage: string | null }; + 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 +46,7 @@ export interface HapticsWebSocketState { } const DEFAULT_OPTIONS: Required> = { - baseUrl: API_BASE_URL, + baseUrls: API_BASE_URLS, initialReconnectDelay: 1000, maxReconnectDelay: 15000, connectionTimeout: 5000, @@ -50,7 +56,8 @@ export class HapticsWebSocket { private options: Required> & Pick; private ws: WebSocket | null = null; private reconnectTimer: ReturnType | null = null; - private connectionTimer: ReturnType | null = null; + // Incremented by every attempt and by disconnect(), so a stale attempt can tell it should stop + private attemptId = 0; private currentReconnectDelay: number; private isDestroyed = false; @@ -83,6 +90,7 @@ export class HapticsWebSocket { /** Disconnect and stop auto-reconnect */ disconnect(): void { this.clearTimers(); + this.attemptId++; if (this.ws) { this.ws.onclose = null; // Prevent reconnect on intentional close this.ws.close(); @@ -115,79 +123,113 @@ export class HapticsWebSocket { if (this.isDestroyed) return; this.clearTimers(); + const attempt = ++this.attemptId; this.updateState( this._state.connectionState === 'disconnected' ? 'connecting' : 'reconnecting', 'none', null ); - // First, validate the service is correct by checking the health endpoint - const validation = await this.validateService(); - if (!validation.valid) { - this.updateState('disconnected', validation.errorType, validation.errorMessage); - this.scheduleReconnect(); - return; + // Try each endpoint in order: it must answer the health check AND accept the WebSocket, + // since a browser can allow one and block the other. + let failure: ServiceFailure | null = null; + for (const baseUrl of this.options.baseUrls) { + const validation = await this.validateService(baseUrl); + if (attempt !== this.attemptId) return; // disconnected or superseded meanwhile + + const result = validation.valid + ? await this.openWebSocket(baseUrl.replace(/^http/, 'ws') + '/ws') + : validation; + if (attempt !== this.attemptId) { + if ('ws' in result) result.ws.close(); + return; + } + + if ('ws' in result) { + this.adopt(result.ws); + return; + } + + // Report the most specific error (anything over "connection refused") + if (!failure || failure.errorType === 'connection_refused') { + failure = result; + } } - // Now attempt WebSocket connection - const wsUrl = this.options.baseUrl.replace(/^http/, 'ws') + '/ws'; + failure ??= { valid: false, errorType: 'connection_refused', errorMessage: 'Cannot connect to haptics service' }; + this.updateState('disconnected', failure.errorType, failure.errorMessage); + this.scheduleReconnect(); + } - try { - this.ws = new WebSocket(wsUrl); - this.ws.binaryType = 'arraybuffer'; - - // Set connection timeout - this.connectionTimer = setTimeout(() => { - if (this.ws && this.ws.readyState === WebSocket.CONNECTING) { - this.ws.close(); - this.updateState('disconnected', 'timeout', 'Connection timed out'); - this.scheduleReconnect(); - } - }, this.options.connectionTimeout); + /** Resolves with the open socket, or with why it failed to open. */ + private openWebSocket(url: string): Promise<{ ws: WebSocket } | ServiceFailure> { + return new Promise((resolve) => { + let ws: WebSocket; + try { + ws = new WebSocket(url); + } catch (error) { + resolve({ valid: false, errorType: 'websocket_error', errorMessage: String(error) }); + return; + } + ws.binaryType = 'arraybuffer'; - this.ws.onopen = () => { - this.clearTimers(); - this.currentReconnectDelay = this.options.initialReconnectDelay; // Reset backoff - this.updateState('connected', 'none', null); - }; + const timer = setTimeout(() => { + ws.onopen = ws.onclose = null; + ws.close(); + resolve({ valid: false, errorType: 'timeout', errorMessage: 'Connection timed out' }); + }, this.options.connectionTimeout); - this.ws.onclose = (event) => { - this.clearTimers(); - if (!this.isDestroyed) { - const errorMessage = event.reason || 'Connection closed'; - this.updateState('disconnected', 'websocket_error', errorMessage); - this.scheduleReconnect(); - } + ws.onopen = () => { + clearTimeout(timer); + ws.onopen = ws.onclose = null; + resolve({ ws }); }; - this.ws.onerror = () => { - // Error details are limited in browser for security - // The onclose handler will fire after this + // Error details are limited in browser for security; onclose always follows onerror + ws.onclose = (event) => { + clearTimeout(timer); + resolve({ valid: false, errorType: 'websocket_error', errorMessage: event.reason || 'WebSocket connection failed' }); }; + }); + } - } catch (error) { - this.updateState('disconnected', 'websocket_error', String(error)); - this.scheduleReconnect(); + private adopt(ws: WebSocket): void { + this.clearTimers(); // a retry scheduled by a socket closing meanwhile is no longer needed + if (this.ws) { + this.ws.onclose = null; + this.ws.close(); } + this.ws = ws; + this.currentReconnectDelay = this.options.initialReconnectDelay; // Reset backoff + + ws.onclose = (event) => { + if (this.ws !== ws) return; // replaced by a newer connection + this.ws = null; + if (!this.isDestroyed) { + this.updateState('disconnected', 'websocket_error', event.reason || 'Connection closed'); + this.scheduleReconnect(); + } + }; + + this.updateState('connected', 'none', null); } - private async validateService(): Promise<{ valid: boolean; errorType: ErrorType; errorMessage: string | null }> { + private async validateService(baseUrl: string): Promise { 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, }); - clearTimeout(timeoutId); - if (!response.ok) { return { valid: false, errorType: 'wrong_service', errorMessage: `Unexpected status: ${response.status}` }; } const data = await response.json(); + clearTimeout(timeoutId); if (data.service !== 'HapticWebPlugin') { return { @@ -197,7 +239,7 @@ export class HapticsWebSocket { }; } - return { valid: true, errorType: 'none', errorMessage: null }; + return { valid: true }; } catch (error) { clearTimeout(timeoutId); @@ -242,10 +284,6 @@ export class HapticsWebSocket { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } - if (this.connectionTimer) { - clearTimeout(this.connectionTimer); - this.connectionTimer = null; - } } private updateState(connectionState: ConnectionState, errorType: ErrorType, errorMessage: string | null): void { diff --git a/web-demo/src/lib/haptics.ts b/web-demo/src/lib/haptics.ts index 8a75f2c..00f69f8 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,29 +39,63 @@ 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) { + // AbortController rather than AbortSignal.timeout(), which Safari only has from 16 + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 3000); + try { + const response = await fetch(baseUrl + '/', { method: 'GET', signal: controller.signal }); + if (response.ok && (await response.json())?.service === 'HapticWebPlugin') { + return baseUrl; + } + } catch { + // Not reachable from this page (not running, blocked as mixed content, or timed out); try the next one + } finally { + clearTimeout(timeoutId); + } + } + 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) { + resolvedApiBase = null; // something else may own the port now; re-probe next time console.error('Failed to trigger waveform:', response.statusText); return null; } return await response.json(); } catch (error) { + resolvedApiBase = null; // the service may have moved (e.g. restarted without HTTPS) console.error('Failed to trigger waveform:', error); return null; } } export async function healthCheck(): 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..44a0387 100644 --- a/web-demo/src/routes/api/+page.svelte +++ b/web-demo/src/routes/api/+page.svelte @@ -1,7 +1,7 @@