Skip to content

Commit

Permalink
fix: Add support for IPv6 loopback and all IPv4 addresses (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
Artur- authored Apr 2, 2023
1 parent 7e5e2f6 commit 6a874bc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 15 additions & 1 deletion frontend/packages/common-frontend/src/ConnectionState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
15 changes: 14 additions & 1 deletion frontend/packages/common-frontend/test/ConnectionState.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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;
});

});

0 comments on commit 6a874bc

Please sign in to comment.