From 6a874bc2bda123ca3f85d4d788874b2cad0aeddc Mon Sep 17 00:00:00 2001 From: Artur Date: Sun, 2 Apr 2023 19:08:56 +0300 Subject: [PATCH] fix: Add support for IPv6 loopback and all IPv4 addresses (#14) --- .../common-frontend/src/ConnectionState.ts | 16 +++++++++++++++- .../common-frontend/test/ConnectionState.test.ts | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/frontend/packages/common-frontend/src/ConnectionState.ts b/frontend/packages/common-frontend/src/ConnectionState.ts index 8287e29..6b0befa 100644 --- a/frontend/packages/common-frontend/src/ConnectionState.ts +++ b/frontend/packages/common-frontend/src/ConnectionState.ts @@ -122,10 +122,24 @@ export class ConnectionStateStore { } } +export const isLocalhost = (hostname: string) => { + if (hostname === 'localhost') { + return true; + } + if (hostname === '[::1]') { + return true; + } + if (hostname.match(/^127\.\d+\.\d+\.\d+$/)) { + return true; + } + + return false; +}; + const $wnd = window as any; if (!$wnd.Vaadin?.connectionState) { let online; - if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') { + if (isLocalhost(window.location.hostname)) { // We do not know if we are online or not as we cannot trust navigator.onLine which checks availability of a network connection. Better to assume online so localhost apps can work online = true; } else { diff --git a/frontend/packages/common-frontend/test/ConnectionState.test.ts b/frontend/packages/common-frontend/test/ConnectionState.test.ts index 9eaa055..70deed3 100644 --- a/frontend/packages/common-frontend/test/ConnectionState.test.ts +++ b/frontend/packages/common-frontend/test/ConnectionState.test.ts @@ -1,6 +1,6 @@ import { assert, expect } from '@open-wc/testing'; import sinon from 'sinon'; -import { ConnectionState, ConnectionStateStore } from '../src'; +import { ConnectionState, ConnectionStateStore, isLocalhost } from '../src'; describe('ConnectionStateStore', () => { it('should call state change listeners when transitioning between states', () => { @@ -157,4 +157,17 @@ describe('ConnectionStateStore', () => { navigatorStub.restore(); } }); + it('should know which hosts are localhost', async () => { + expect(isLocalhost("localhost")).to.be.true; + expect(isLocalhost("127.0.0.1")).to.be.true; + expect(isLocalhost("127.0.0.2")).to.be.true; + expect(isLocalhost("127.1.2.3")).to.be.true; + expect(isLocalhost("[::1]")).to.be.true; + expect(isLocalhost("::1")).to.be.false; + expect(isLocalhost("127.0.0.1.com")).to.be.false; + expect(isLocalhost("foo127.0.0.1")).to.be.false; + expect(isLocalhost("localhost.com")).to.be.false; + expect(isLocalhost("my.localhost")).to.be.false; + }); + });