From 9a540a5e22e05109d0d9e46c7cd051428a5644a3 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sat, 18 Nov 2023 17:08:16 +0100 Subject: [PATCH] Treat non-localhost non-secure WebSocket as not supported in browsers (#1360) * Treat non-localhost non-secure WebSocket as not supported in browsers * PR link * Oops, fix check --- wasm-node/CHANGELOG.md | 2 +- .../javascript/src/no-auto-bytecode-browser.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/wasm-node/CHANGELOG.md b/wasm-node/CHANGELOG.md index 56e4ffeda8..091267797f 100644 --- a/wasm-node/CHANGELOG.md +++ b/wasm-node/CHANGELOG.md @@ -4,7 +4,7 @@ ### Changed -- Addresses that are not supported by the host platform are now ignored during the discovery process. For example, TCP/IP connections are ignored while in a browser. This avoids populating the address book with peers that we know we can't connect to anyway. ([#1359](https://github.com/smol-dot/smoldot/pull/1359)) +- Addresses that are not supported by the host platform are now ignored during the discovery process. For example, TCP/IP connections are ignored while in a browser. This avoids populating the address book with peers that we know we can't connect to anyway. ([#1359](https://github.com/smol-dot/smoldot/pull/1359), [#1360](https://github.com/smol-dot/smoldot/pull/1360)) ## 2.0.10 - 2023-11-17 diff --git a/wasm-node/javascript/src/no-auto-bytecode-browser.ts b/wasm-node/javascript/src/no-auto-bytecode-browser.ts index dbce9f5442..95633931dc 100644 --- a/wasm-node/javascript/src/no-auto-bytecode-browser.ts +++ b/wasm-node/javascript/src/no-auto-bytecode-browser.ts @@ -45,6 +45,20 @@ export { export function startWithBytecode(options: ClientOptionsWithBytecode): Client { options.forbidTcp = true; + // When in a secure context, browsers refuse to open non-secure WebSocket connections to + // non-localhost. There is an exception if the page is localhost, in which case all connections + // are allowed. + // Detecting this ahead of time is better for the overall health of the client, as it will + // avoid storing in memory addresses that it knows it can't connect to. + // The condition below is a hint, and false-positives or false-negatives are not fundamentally + // an issue. + if ((typeof isSecureContext === 'boolean' && isSecureContext) && typeof location !== undefined) { + const loc = location.toString(); + if (loc.indexOf('localhost') !== -1 && loc.indexOf('127.0.0.1') !== -1 && loc.indexOf('::1') !== -1) { + options.forbidNonLocalWs = true; + } + } + return innerStart(options, options.bytecode, { performanceNow: () => { return performance.now()