From 50cefcb4599cf4f2aa0025ea7e8f243c582a1ee1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Pardou-Piquemal?= Date: Wed, 10 Jun 2020 21:46:56 +0200 Subject: [PATCH] Add frontend component tests (#144) * Install react-testing-library * Add some trivial tests with snapshot * Add File transfer tests * Add Home component test * Add Chat tests * Add tests for nav * 100% coverage for About component * 100% coverage room link * 100% coverage for RoomLocked * 100% coverage for T component * 100% coverage Settings * More 90% coverage for Chat component * Ignore some file from coverage * 100% coverage fo redux actions * 100% coverage for translations * Near 100% coverage for reducer * Better coverage for Home component * Run tests in circleCI --- .circleci/config.yml | 45 +- client/.env.dist | 3 +- client/package.json | 10 +- client/src/actions/app.test.js | 53 ++ client/src/actions/encrypted_messages.test.js | 49 ++ client/src/actions/index.js | 2 + .../src/actions/unencrypted_messages.test.js | 125 +++ client/src/api/config.js | 1 + client/src/api/generator.js | 1 + client/src/components/About/About.test.js | 52 ++ .../About/__snapshots__/About.test.js.snap | 513 +++++++++++ client/src/components/Chat/Chat.js | 297 +++++++ client/src/components/Chat/Chat.test.js | 262 +++++- .../Chat/__snapshots__/Chat.test.js.snap | 49 +- client/src/components/Chat/index.js | 279 +----- .../components/Connecting/Connecting.test.js | 9 + .../__snapshots__/Connecting.test.js.snap | 9 + .../FileTransfer/FileTransfer.test.js | 90 ++ .../__snapshots__/FileTransfer.test.js.snap | 38 + client/src/components/FileTransfer/index.js | 2 +- client/src/components/Home/Activity.test.js | 201 +++++ client/src/components/Home/ActivityList.js | 2 +- .../src/components/Home/ActivityList.test.js | 160 ++++ client/src/components/Home/Home.js | 1 + client/src/components/Home/Home.test.js | 73 ++ .../Home/__snapshots__/Activity.test.js.snap | 269 ++++++ .../__snapshots__/ActivityList.test.js.snap | 235 +++++ .../Home/__snapshots__/Home.test.js.snap | 365 ++++++++ client/src/components/Message/Message.test.js | 15 + .../__snapshots__/Message.test.js.snap | 32 + client/src/components/Nav/Nav.test.js | 303 +++++++ .../Nav/__snapshots__/Nav.test.js.snap | 531 +++++++++++ client/src/components/Nav/index.js | 106 +-- client/src/components/Notice/Notice.test.js | 19 +- .../Notice/__snapshots__/Notice.test.js.snap | 20 +- .../src/components/RoomLink/RoomLink.test.js | 68 ++ .../__snapshots__/RoomLink.test.js.snap | 59 ++ client/src/components/RoomLink/index.js | 56 +- .../components/RoomLocked/RoomLocked.test.js | 8 + .../__snapshots__/RoomLocked.test.js.snap | 9 + .../src/components/Settings/Settings.test.js | 70 ++ .../__snapshots__/Settings.test.js.snap | 157 ++++ client/src/components/T/T.js | 32 + client/src/components/T/T.test.js | 33 + .../components/T/__snapshots__/T.test.js.snap | 35 + client/src/components/T/index.js | 40 +- .../src/components/Username/Username.test.js | 10 + .../__snapshots__/Username.test.js.snap | 12 + client/src/components/Welcome/Welcome.test.js | 12 + .../__snapshots__/Welcome.test.js.snap | 106 +++ client/src/config/env.js | 1 + client/src/i18n/i18n.test.js | 15 +- client/src/index.js | 1 + client/src/index.test.js | 5 + client/src/reducers/activities.test.js | 183 ++++ client/src/reducers/app.test.js | 72 ++ client/src/reducers/index.js | 1 + client/src/reducers/room.test.js | 154 ++++ client/src/reducers/user.test.js | 29 + client/src/serviceWorker.js | 1 + client/src/setupTests.js | 6 +- client/src/store/index.js | 1 + client/src/stylesheets/postcss.config.js | 2 + client/src/test/setup.js | 7 +- client/yarn.lock | 829 +++++++++++++++++- package.json | 4 +- 66 files changed, 5777 insertions(+), 462 deletions(-) create mode 100644 client/src/actions/app.test.js create mode 100644 client/src/actions/encrypted_messages.test.js create mode 100644 client/src/actions/unencrypted_messages.test.js create mode 100644 client/src/components/About/About.test.js create mode 100644 client/src/components/About/__snapshots__/About.test.js.snap create mode 100644 client/src/components/Chat/Chat.js create mode 100644 client/src/components/Connecting/Connecting.test.js create mode 100644 client/src/components/Connecting/__snapshots__/Connecting.test.js.snap create mode 100644 client/src/components/FileTransfer/FileTransfer.test.js create mode 100644 client/src/components/FileTransfer/__snapshots__/FileTransfer.test.js.snap create mode 100644 client/src/components/Home/Activity.test.js create mode 100644 client/src/components/Home/ActivityList.test.js create mode 100644 client/src/components/Home/Home.test.js create mode 100644 client/src/components/Home/__snapshots__/Activity.test.js.snap create mode 100644 client/src/components/Home/__snapshots__/ActivityList.test.js.snap create mode 100644 client/src/components/Home/__snapshots__/Home.test.js.snap create mode 100644 client/src/components/Message/Message.test.js create mode 100644 client/src/components/Message/__snapshots__/Message.test.js.snap create mode 100644 client/src/components/Nav/Nav.test.js create mode 100644 client/src/components/Nav/__snapshots__/Nav.test.js.snap create mode 100644 client/src/components/RoomLink/RoomLink.test.js create mode 100644 client/src/components/RoomLink/__snapshots__/RoomLink.test.js.snap create mode 100644 client/src/components/RoomLocked/RoomLocked.test.js create mode 100644 client/src/components/RoomLocked/__snapshots__/RoomLocked.test.js.snap create mode 100644 client/src/components/Settings/Settings.test.js create mode 100644 client/src/components/Settings/__snapshots__/Settings.test.js.snap create mode 100644 client/src/components/T/T.js create mode 100644 client/src/components/T/T.test.js create mode 100644 client/src/components/T/__snapshots__/T.test.js.snap create mode 100644 client/src/components/Username/Username.test.js create mode 100644 client/src/components/Username/__snapshots__/Username.test.js.snap create mode 100644 client/src/components/Welcome/Welcome.test.js create mode 100644 client/src/components/Welcome/__snapshots__/Welcome.test.js.snap create mode 100644 client/src/index.test.js create mode 100644 client/src/reducers/activities.test.js create mode 100644 client/src/reducers/app.test.js create mode 100644 client/src/reducers/room.test.js create mode 100644 client/src/reducers/user.test.js diff --git a/.circleci/config.yml b/.circleci/config.yml index ff23b07..403f576 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,18 +1,10 @@ # Javascript Node CircleCI 2.0 configuration file # -# Check https://circleci.com/docs/2.0/language-javascript/ for more details -# -version: 2 -jobs: - build: - docker: - # specify the version you desire here - - image: circleci/node:8.10 - # Specify service dependencies here if necessary - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - # - image: circleci/mongo:3.4.4 +jobs: + test-job: + docker: + - image: 'circleci/node:lts' working_directory: ~/repo @@ -22,15 +14,34 @@ jobs: # Download and cache dependencies - restore_cache: keys: - - v1-dependencies-{{ checksum "yarn.lock" }} + - dependencies-{{ checksum "yarn.lock" }} # fallback to using the latest cache if no exact match is found - - v1-dependencies- + - dependencies- - - run: yarn install + - run: yarn setup - save_cache: paths: - node_modules - key: v1-dependencies-{{ checksum "yarn.lock" }} + - client/node_modules + - server/node_modules + key: dependencies-{{ checksum "yarn.lock" }} - - run: yarn test \ No newline at end of file + - run: + command: yarn test + environment: + TZ: UTC + REACT_APP_COMMIT_SHA: some_sha + + - store_artifacts: # For coverage report + path: client/coverage + +orbs: # declare what orbs we are going to use + node: circleci/node@2.0.2 # the node orb provides common node-related configuration + +version: 2.1 + +workflows: + tests: + jobs: + - test-job diff --git a/client/.env.dist b/client/.env.dist index 2695add..07e63f9 100644 --- a/client/.env.dist +++ b/client/.env.dist @@ -1,4 +1,5 @@ REACT_APP_API_HOST=localhost REACT_APP_API_PROTOCOL=http REACT_APP_API_PORT=3001 -REACT_APP_COMMIT_SHA=some_sha \ No newline at end of file +REACT_APP_COMMIT_SHA=some_sha +TZ=UTC diff --git a/client/package.json b/client/package.json index 4054d9a..bdd5122 100644 --- a/client/package.json +++ b/client/package.json @@ -43,7 +43,8 @@ "scripts": { "start": "react-scripts start", "build": "react-scripts build", - "test": "react-scripts test", + "test": "react-scripts test --env=jest-environment-jsdom-sixteen", + "coverage": "react-scripts test --env=jest-environment-jsdom-sixteen --coverage --watchAll=false", "eject": "react-scripts eject" }, "eslintConfig": { @@ -62,8 +63,13 @@ ] }, "devDependencies": { + "@peculiar/webcrypto": "^1.1.1", + "@testing-library/jest-dom": "^5.5.0", + "@testing-library/react": "^10.0.4", "enzyme": "^3.9.0", "enzyme-adapter-react-16": "^1.12.1", - "enzyme-to-json": "^3.3.5" + "enzyme-to-json": "^3.3.5", + "jest-environment-jsdom-sixteen": "^1.0.3", + "jest-fetch-mock": "^3.0.3" } } diff --git a/client/src/actions/app.test.js b/client/src/actions/app.test.js new file mode 100644 index 0000000..5589671 --- /dev/null +++ b/client/src/actions/app.test.js @@ -0,0 +1,53 @@ +import * as actions from './app'; + +describe('App actions', () => { + it('should create an action to scroll to bottom', () => { + expect(actions.setScrolledToBottom('test')).toEqual({ + type: 'SET_SCROLLED_TO_BOTTOM', + payload: 'test', + }); + }); + + it('should create an action to close modal', () => { + expect(actions.closeModal()).toEqual({ + type: 'CLOSE_MODAL', + }); + }); + + it('should create an action to open modal', () => { + expect(actions.openModal('test')).toEqual({ + type: 'OPEN_MODAL', + payload: 'test', + }); + }); + + it('should create an action to clear activities', () => { + const mockDispatch = jest.fn(); + + actions.clearActivities()(mockDispatch); + + expect(mockDispatch).toHaveBeenLastCalledWith({ + type: 'CLEAR_ACTIVITIES', + }); + }); + it('should create all actions', () => { + const mockDispatch = jest.fn(); + + const actionsResults = [ + [actions.toggleWindowFocus('test'), 'TOGGLE_WINDOW_FOCUS'], + [actions.showNotice('test'), 'SHOW_NOTICE'], + [actions.toggleSoundEnabled('test'), 'TOGGLE_SOUND_ENABLED'], + [actions.toggleSocketConnected('test'), 'TOGGLE_SOCKET_CONNECTED'], + [actions.createUser('test'), 'CREATE_USER'], + [actions.setLanguage('test'), 'CHANGE_LANGUAGE'], + ]; + + actionsResults.forEach(([action, type]) => { + action(mockDispatch); + expect(mockDispatch).toHaveBeenLastCalledWith({ + type, + payload: 'test', + }); + }); + }); +}); diff --git a/client/src/actions/encrypted_messages.test.js b/client/src/actions/encrypted_messages.test.js new file mode 100644 index 0000000..9687322 --- /dev/null +++ b/client/src/actions/encrypted_messages.test.js @@ -0,0 +1,49 @@ +import * as actions from './encrypted_messages'; +import { getSocket } from 'utils/socket'; +import { prepare as prepareMessage, process as processMessage } from 'utils/message'; + +jest.mock('utils/message', () => { + return { + prepare: jest + .fn() + .mockResolvedValue({ original: { type: 'messageType', payload: 'test' }, toSend: 'encryptedpayload' }), + process: jest.fn().mockResolvedValue({ type: 'messageType', payload: 'test' }), + }; +}); + +const mockEmit = jest.fn(); + +jest.mock('utils/socket', () => { + return { + getSocket: jest.fn().mockImplementation(() => ({ + emit: mockEmit, + })), + }; +}); + +describe('Encrypted messages actions', () => { + it('should create an action to send message', async () => { + const mockDispatch = jest.fn(); + + await actions.sendEncryptedMessage({ payload: 'payload' })(mockDispatch, jest.fn().mockReturnValue({ state: {} })); + + expect(prepareMessage).toHaveBeenLastCalledWith({ payload: 'payload' }, { state: {} }); + expect(mockDispatch).toHaveBeenLastCalledWith({ payload: 'test', type: 'SEND_ENCRYPTED_MESSAGE_messageType' }); + expect(getSocket().emit).toHaveBeenLastCalledWith('ENCRYPTED_MESSAGE', 'encryptedpayload'); + }); + + it('should create an action to receive message', async () => { + const mockDispatch = jest.fn(); + + await actions.receiveEncryptedMessage({ payload: 'encrypted' })( + mockDispatch, + jest.fn().mockReturnValue({ state: {} }), + ); + + expect(processMessage).toHaveBeenLastCalledWith({ payload: 'encrypted' }, { state: {} }); + expect(mockDispatch).toHaveBeenLastCalledWith({ + payload: { payload: 'test', state: { state: {} } }, + type: 'RECEIVE_ENCRYPTED_MESSAGE_messageType', + }); + }); +}); diff --git a/client/src/actions/index.js b/client/src/actions/index.js index 3504084..bb6fcbf 100644 --- a/client/src/actions/index.js +++ b/client/src/actions/index.js @@ -1,3 +1,5 @@ +/* istanbul ignore file */ + export * from './app' export * from './unencrypted_messages' export * from './encrypted_messages' diff --git a/client/src/actions/unencrypted_messages.test.js b/client/src/actions/unencrypted_messages.test.js new file mode 100644 index 0000000..dc52cd5 --- /dev/null +++ b/client/src/actions/unencrypted_messages.test.js @@ -0,0 +1,125 @@ +import * as actions from './unencrypted_messages'; +import { getSocket } from 'utils/socket'; + +const mockEmit = jest.fn((_type, _null, callback) => { + callback({ isLocked: true }); +}); + +jest.mock('utils/socket', () => { + return { + getSocket: jest.fn().mockImplementation(() => ({ + emit: mockEmit, + })), + }; +}); + +describe('Reveice unencrypted message actions', () => { + it('should create no action', () => { + const mockDispatch = jest.fn(); + actions.receiveUnencryptedMessage('FAKE')(mockDispatch, jest.fn().mockReturnValue({})); + expect(mockDispatch).not.toHaveBeenCalled(); + }); + + it('should create user enter action', () => { + const mockDispatch = jest.fn(); + actions.receiveUnencryptedMessage('USER_ENTER', 'test')(mockDispatch, jest.fn().mockReturnValue({ state: {} })); + expect(mockDispatch).toHaveBeenLastCalledWith({ type: 'USER_ENTER', payload: 'test' }); + }); + + it('should create user exit action', () => { + const mockDispatch = jest.fn(); + const state = { + room: { + members: [ + { publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan' }, + { publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan' }, + { publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'dan' }, + ], + }, + }; + const mockGetState = jest.fn().mockReturnValue(state); + const payload1 = [ + { publicKey: { n: 'alankey' } }, + { publicKey: { n: 'dankey' } }, + { publicKey: { n: 'alicekey' } }, + ]; + const payload2 = [{ publicKey: { n: 'dankey' } }, { publicKey: { n: 'alicekey' } }]; + + // Nobody left + actions.receiveUnencryptedMessage('USER_EXIT', payload1)(mockDispatch, mockGetState); + + expect(mockDispatch).not.toHaveBeenCalled(); + + actions.receiveUnencryptedMessage('USER_EXIT', payload2)(mockDispatch, mockGetState); + expect(mockDispatch).toHaveBeenLastCalledWith({ + payload: { + id: 'alankey', + members: [{ publicKey: { n: 'dankey' } }, { publicKey: { n: 'alicekey' } }], + username: 'alan', + }, + type: 'USER_EXIT', + }); + }); + + it('should create receive toggle lock room action', () => { + const mockDispatch = jest.fn(); + const state = { + room: { + members: [ + { publicKey: { n: 'alankey' }, id: 'idalan', username: 'alan' }, + { publicKey: { n: 'dankey' }, id: 'iddan', username: 'dan' }, + ], + }, + }; + const mockGetState = jest.fn().mockReturnValue(state); + const payload = { publicKey: { n: 'alankey' } }; + + actions.receiveUnencryptedMessage('TOGGLE_LOCK_ROOM', payload)(mockDispatch, mockGetState); + expect(mockDispatch).toHaveBeenLastCalledWith({ + payload: { id: 'idalan', locked: undefined, username: 'alan' }, + type: 'RECEIVE_TOGGLE_LOCK_ROOM', + }); + }); + + it('should create receive toggle lock room action', () => { + const mockDispatch = jest.fn(); + const state = { + user: { + username: 'alan', + id: 'idalan', + }, + }; + const mockGetState = jest.fn().mockReturnValue(state); + + actions.sendUnencryptedMessage('TOGGLE_LOCK_ROOM')(mockDispatch, mockGetState); + expect(mockDispatch).toHaveBeenLastCalledWith({ + payload: { locked: true, sender: 'idalan', username: 'alan' }, + type: 'TOGGLE_LOCK_ROOM', + }); + }); +}); + +describe('Send unencrypted message actions', () => { + it('should create no action', () => { + const mockDispatch = jest.fn(); + actions.sendUnencryptedMessage('FAKE')(mockDispatch, jest.fn().mockReturnValue({})); + expect(mockDispatch).not.toHaveBeenCalled(); + }); + + it('should create toggle lock room action', () => { + const mockDispatch = jest.fn(); + const state = { + user: { + username: 'alan', + id: 'idalan', + }, + }; + const mockGetState = jest.fn().mockReturnValue(state); + + actions.sendUnencryptedMessage('TOGGLE_LOCK_ROOM')(mockDispatch, mockGetState); + expect(mockDispatch).toHaveBeenLastCalledWith({ + payload: { locked: true, sender: 'idalan', username: 'alan' }, + type: 'TOGGLE_LOCK_ROOM', + }); + }); +}); diff --git a/client/src/api/config.js b/client/src/api/config.js index 30e1c50..0aa2bd1 100644 --- a/client/src/api/config.js +++ b/client/src/api/config.js @@ -1,3 +1,4 @@ +/* istanbul ignore file */ let host let protocol let port diff --git a/client/src/api/generator.js b/client/src/api/generator.js index 9dd44f1..293c12b 100644 --- a/client/src/api/generator.js +++ b/client/src/api/generator.js @@ -1,3 +1,4 @@ +/* istanbul ignore file */ import config from './config' export default (resourceName = '') => { diff --git a/client/src/components/About/About.test.js b/client/src/components/About/About.test.js new file mode 100644 index 0000000..74846e3 --- /dev/null +++ b/client/src/components/About/About.test.js @@ -0,0 +1,52 @@ +import React from 'react'; +import { render, fireEvent, waitFor } from '@testing-library/react'; +import About from '.'; +import fetchMock from 'jest-fetch-mock'; + +jest.useFakeTimers(); + +// Mock Api generator + +jest.mock('../../api/generator', () => { + return path => { + return `http://fakedomain/${path}`; + }; +}); + +describe('About component', () => { + afterEach(() => { + fetchMock.resetMocks(); + }); + + it('should display', async () => { + const { asFragment } = render(); + + expect(asFragment()).toMatchSnapshot(); + }); + + it('should report abuse', async () => { + const { getByText, queryByText } = render(); + + expect(queryByText('Thank you!')).not.toBeInTheDocument(); + + fireEvent.click(getByText('Submit')); + + expect(fetchMock).toHaveBeenCalledWith('http://fakedomain/abuse/test', { method: 'POST' }); + + expect(getByText('Thank you!')).toBeInTheDocument(); + }); + + it('should change room id', async () => { + const { getByPlaceholderText, getByText, queryByText } = render(); + + expect(queryByText('Thank you!')).not.toBeInTheDocument(); + + fireEvent.change(getByPlaceholderText('Room ID'), { target: { value: 'newRoomName' } }); + + jest.runAllTimers(); + + fireEvent.click(getByText('Submit')); + + expect(fetchMock).toHaveBeenLastCalledWith('http://fakedomain/abuse/newRoomName', { method: 'POST' }); + }); +}); diff --git a/client/src/components/About/__snapshots__/About.test.js.snap b/client/src/components/About/__snapshots__/About.test.js.snap new file mode 100644 index 0000000..5d3841a --- /dev/null +++ b/client/src/components/About/__snapshots__/About.test.js.snap @@ -0,0 +1,513 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`About component should display 1`] = ` + +
+ +
+

+ Version +

+

+ Commit SHA: + + some_sha + +

+
+
+

+ Software +

+

+ This software uses the + + Web Cryptography API + + to encrypt data which is transferred using + + secure WebSockets + + . Messages are never stored on a server or sent over the wire in plain-text. +

+

+ We believe in privacy and transparency.   + + View the source code and documentation on GitHub. + +

+
+
+

+ Report Abuse +

+

+ We encourage you to report problematic content to us. Please keep in mind that to help ensure the safety, confidentiality and security of your messages, we do not have the contents of messages available to us, which limits our ability to verify the report and take action. +

+

+ When needed, you can take a screenshot of the content and share it, along with any available contact info, with appropriate law enforcement authorities. +

+

+ To report any content, email us at abuse[at]darkwire.io or submit the room ID below to report anonymously. +

+
+
+
+ +
+ +
+
+
+
+
+

+ If you feel you or anyone else is in immediate danger, please contact your local emergency services. +

+

+ If you receive content from someone who wishes to hurt themselves, and you're concerned for their safety, please contact your local emergency services or a + + suicide prevention hotline + + . +

+

+ If you receive or encounter content indicating abuse or exploitation of a child, please contact the + + National Center for Missing and Exploited Children (NCMEC) + + . +

+
+
+

+ Acceptable Use Policy +

+

+ This Acceptable Use Policy (this “Policy”) describes prohibited uses of the web services offered by Darkwire and its affiliates (the “Services”) and the website located at https://darkwire.io (the “Darkwire Site”). The examples described in this Policy are not exhaustive. We may modify this Policy at any time by posting a revised version on the Darkwire Site. By using the Services or accessing the Darkwire Site, you agree to the latest version of this Policy. If you violate the Policy or authorize or help others to do so, we may suspend or terminate your use of the Services. +

+ + No Illegal, Harmful, or Offensive Use or Content + +

+ You may not use, or encourage, promote, facilitate or instruct others to use, the Services or Darkwire Site for any illegal, harmful, fraudulent, infringing or offensive use, or to transmit, store, display, distribute or otherwise make available content that is illegal, harmful, fraudulent, infringing or offensive. Prohibited activities or content include: +

+
    +
  • + + Illegal, Harmful or Fraudulent Activities. + + Any activities that are illegal, that violate the rights of others, or that may be harmful to others, our operations or reputation, including disseminating, promoting or facilitating child pornography, offering or disseminating fraudulent goods, services, schemes, or promotions, make-money-fast schemes, ponzi and pyramid schemes, phishing, or pharming. +
  • +
  • + + Infringing Content. + + Content that infringes or misappropriates the intellectual property or proprietary rights of others. +
  • +
  • + + Offensive Content. + + Content that is defamatory, obscene, abusive, invasive of privacy, or otherwise objectionable, including content that constitutes child pornography, relates to bestiality, or depicts non-consensual sex acts. +
  • +
  • + + Harmful Content. + + Content or other computer technology that may damage, interfere with, surreptitiously intercept, or expropriate any system, program, or data, including viruses, Trojan horses, worms, time bombs, or cancelbots. +
  • +
+ + No Security Violations + +
+ You may not use the Services to violate the security or integrity of any network, computer or communications system, software application, or network or computing device (each, a “System”). Prohibited activities include: +
    +
  • + + Unauthorized Access. + + Accessing or using any System without permission, including attempting to probe, scan, or test the vulnerability of a System or to breach any security or authentication measures used by a System. +
  • +
  • + + Interception. + + Monitoring of data or traffic on a System without permission. +
  • +
  • + + Falsification of Origin. + + Forging TCP-IP packet headers, e-mail headers, or any part of a message describing its origin or route. The legitimate use of aliases and anonymous remailers is not prohibited by this provision. +
  • +
+ + No Network Abuse + +
+ You may not make network connections to any users, hosts, or networks unless you have permission to communicate with them. Prohibited activities include: +
    +
  • + + Monitoring or Crawling. + + Monitoring or crawling of a System that impairs or disrupts the System being monitored or crawled. +
  • +
  • + + Denial of Service (DoS). + + Inundating a target with communications requests so the target either cannot respond to legitimate traffic or responds so slowly that it becomes ineffective. +
  • +
  • + + Intentional Interference. + + Interfering with the proper functioning of any System, including any deliberate attempt to overload a system by mail bombing, news bombing, broadcast attacks, or flooding techniques. +
  • +
  • + + Operation of Certain Network Services. + + Operating network services like open proxies, open mail relays, or open recursive domain name servers. +
  • +
  • + + Avoiding System Restrictions. + + Using manual or electronic means to avoid any use limitations placed on a System, such as access and storage restrictions. +
  • +
+ + No E-Mail or Other Message Abuse + +
+ You will not distribute, publish, send, or facilitate the sending of unsolicited mass e-mail or other messages, promotions, advertising, or solicitations (like “spam”), including commercial advertising and informational announcements. You will not alter or obscure mail headers or assume a sender’s identity without the sender’s explicit permission. You will not collect replies to messages sent from another internet service provider if those messages violate this Policy or the acceptable use policy of that provider. + + Our Monitoring and Enforcement + +
+ We reserve the right, but do not assume the obligation, to investigate any violation of this Policy or misuse of the Services or Darkwire Site. We may: +
    +
  • + investigate violations of this Policy or misuse of the Services or Darkwire Site; or +
  • +
  • + remove, disable access to, or modify any content or resource that violates this Policy or any other agreement we have with you for use of the Services or the Darkwire Site. +
  • +
  • + We may report any activity that we suspect violates any law or regulation to appropriate law enforcement officials, regulators, or other appropriate third parties. Our reporting may include disclosing appropriate customer information. We also may cooperate with appropriate law enforcement agencies, regulators, or other appropriate third parties to help with the investigation and prosecution of illegal conduct by providing network and systems information related to alleged violations of this Policy. +
  • +
+ Reporting of Violations of this Policy +
+ If you become aware of any violation of this Policy, you will immediately notify us and provide us with assistance, as requested, to stop or remedy the violation. To report any violation of this Policy, please follow our abuse reporting process. +
+
+

+ Terms of Service ("Terms") +

+

+ Last updated: December 11, 2017 +

+

+ Please read these Terms of Service ("Terms", "Terms of Service") carefully before using the https://darkwire.io website (the "Service") operated by Darkwire ("us", "we", or "our"). +

+

+ Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service. +

+

+ By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the terms then you may not access the Service. +

+ + Links To Other Web Sites + +

+ Our Service may contain links to third-party web sites or services that are not owned or controlled by Darkwire. +

+

+ Darkwire has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Darkwire shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services. +

+

+ We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit. +

+ + Termination + +

+ We may terminate or suspend access to our Service immediately, without prior notice or liability, for any reason whatsoever, including without limitation if you breach the Terms. +

+

+ All provisions of the Terms which by their nature should survive termination shall survive termination, including, without limitation, ownership provisions, warranty disclaimers, indemnity and limitations of liability. +

+ + Governing Law + +

+ These Terms shall be governed and construed in accordance with the laws of New York, United States, without regard to its conflict of law provisions. +

+

+ Our failure to enforce any right or provision of these Terms will not be considered a waiver of those rights. If any provision of these Terms is held to be invalid or unenforceable by a court, the remaining provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us regarding our Service, and supersede and replace any prior agreements we might have between us regarding the Service. +

+
+
+

+ Disclaimer +

+

+ WARNING: Darkwire does not mask IP addresses nor can verify the integrity of parties recieving messages.  Proceed with caution and always confirm recipients beforre starting a chat session. +

+

+ Please also note that + + ALL CHATROOMS + + are public.  Anyone can guess your room URL. If you need a more-private room, use the lock feature or set the URL manually by entering a room ID after "darkwire.io/". +

+
+ + No Warranties; Exclusion of Liability; Indemnification + +

+ + OUR WEBSITE IS OPERATED BY Darkwire ON AN "AS IS," "AS AVAILABLE" BASIS, WITHOUT REPRESENTATIONS OR WARRANTIES OF ANY KIND. TO THE FULLEST EXTENT PERMITTED BY LAW, Darkwire SPECIFICALLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NONINFRINGEMENT FOR OUR WEBSITE AND ANY CONTRACTS AND SERVICES YOU PURCHASE THROUGH IT. Darkwire SHALL NOT HAVE ANY LIABILITY OR RESPONSIBILITY FOR ANY ERRORS OR OMISSIONS IN THE CONTENT OF OUR WEBSITE, FOR CONTRACTS OR SERVICES SOLD THROUGH OUR WEBSITE, FOR YOUR ACTION OR INACTION IN CONNECTION WITH OUR WEBSITE OR FOR ANY DAMAGE TO YOUR COMPUTER OR DATA OR ANY OTHER DAMAGE YOU MAY INCUR IN CONNECTION WITH OUR WEBSITE. YOUR USE OF OUR WEBSITE AND ANY CONTRACTS OR SERVICES ARE AT YOUR OWN RISK. IN NO EVENT SHALL EITHER Darkwire OR THEIR AGENTS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OUR WEBSITE, CONTRACTS AND SERVICES PURCHASED THROUGH OUR WEBSITE, THE DELAY OR INABILITY TO USE OUR WEBSITE OR OTHERWISE ARISING IN CONNECTION WITH OUR WEBSITE, CONTRACTS OR RELATED SERVICES, WHETHER BASED ON CONTRACT, TORT, STRICT LIABILITY OR OTHERWISE, EVEN IF ADVISED OF THE POSSIBILITY OF ANY SUCH DAMAGES. IN NO EVENT SHALL Darkwire’s LIABILITY FOR ANY DAMAGE CLAIM EXCEED THE AMOUNT PAID BY YOU TO Darkwire FOR THE TRANSACTION GIVING RISE TO SUCH DAMAGE CLAIM. + +

+

+ + SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. + +

+

+ + WITHOUT LIMITING THE FOREGOING, Darkwire DO NOT REPRESENT OR WARRANT THAT THE INFORMATION ON THE WEBITE IS ACCURATE, COMPLETE, RELIABLE, USEFUL, TIMELY OR CURRENT OR THAT OUR WEBSITE WILL OPERATE WITHOUT INTERRUPTION OR ERROR. + +

+

+ + YOU AGREE THAT ALL TIMES, YOU WILL LOOK TO ATTORNEYS FROM WHOM YOU PURCHASE SERVICES FOR ANY CLAIMS OF ANY NATURE, INCLUDING LOSS, DAMAGE, OR WARRANTY. Darkwire AND THEIR RESPECTIVE AFFILIATES MAKE NO REPRESENTATION OR GUARANTEES ABOUT ANY CONTRACTS AND SERVICES OFFERED THROUGH OUR WEBSITE. + +

+

+ + Darkwire MAKES NO REPRESENTATION THAT CONTENT PROVIDED ON OUR WEBSITE, CONTRACTS, OR RELATED SERVICES ARE APPLICABLE OR APPROPRIATE FOR USE IN ALL JURISDICTIONS. + +

+ + Indemnification + +

+ You agree to defend, indemnify and hold Darkwire harmless from and against any and all claims, damages, costs and expenses, including attorneys' fees, arising from or related to your use of our Website or any Contracts or Services you purchase through it. +

+ + Changes + +

+ We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will try to provide at least 30 days notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion. +

+

+ By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, please stop using the Service. +

+ + Contact Us + +

+ If you have any questions about these Terms, please contact us at hello[at]darkwire.io. +

+
+
+

+ Contact +

+

+ Questions/comments? Email us at hello[at]darkwire.io +

+

+ Found a bug or want a new feature? + + Open a ticket on Github + + . +

+
+ +
+
+`; diff --git a/client/src/components/Chat/Chat.js b/client/src/components/Chat/Chat.js new file mode 100644 index 0000000..9790b44 --- /dev/null +++ b/client/src/components/Chat/Chat.js @@ -0,0 +1,297 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import sanitizeHtml from 'sanitize-html'; +import FileTransfer from 'components/FileTransfer'; +import { CornerDownRight } from 'react-feather'; +import { getSelectedText, hasTouchSupport } from '../../utils/dom'; + +// Disable for now +// import autosize from 'autosize' + +export class Chat extends Component { + constructor(props) { + super(props); + this.state = { + message: '', + touchSupport: hasTouchSupport, + shiftKeyDown: false, + }; + + this.commands = [ + { + command: 'nick', + description: 'Changes nickname.', + paramaters: ['{username}'], + usage: '/nick {username}', + scope: 'global', + action: params => { + // eslint-disable-line + let newUsername = params.join(' ') || ''; // eslint-disable-line + + // Remove things that arent digits or chars + newUsername = newUsername.replace(/[^A-Za-z0-9]/g, '-'); + + const errors = []; + + if (!newUsername.trim().length) { + errors.push('Username cannot be blank'); + } + + if (newUsername.toString().length > 16) { + errors.push('Username cannot be greater than 16 characters'); + } + + if (!newUsername.match(/^[A-Z]/i)) { + errors.push('Username must start with a letter'); + } + + if (errors.length) { + return this.props.showNotice({ + message: `${errors.join(', ')}`, + level: 'error', + }); + } + + this.props.sendEncryptedMessage({ + type: 'CHANGE_USERNAME', + payload: { + id: this.props.userId, + newUsername, + currentUsername: this.props.username, + }, + }); + }, + }, + { + command: 'help', + description: 'Shows a list of commands.', + paramaters: [], + usage: '/help', + scope: 'local', + action: params => { + // eslint-disable-line + const validCommands = this.commands.map(command => `/${command.command}`); + this.props.showNotice({ + message: `Valid commands: ${validCommands.sort().join(', ')}`, + level: 'info', + }); + }, + }, + { + command: 'me', + description: 'Invoke virtual action', + paramaters: ['{action}'], + usage: '/me {action}', + scope: 'global', + action: params => { + // eslint-disable-line + const actionMessage = params.join(' '); + if (!actionMessage.trim().length) { + return false; + } + + this.props.sendEncryptedMessage({ + type: 'USER_ACTION', + payload: { + action: actionMessage, + }, + }); + }, + }, + { + command: 'clear', + description: 'Clears the chat screen', + paramaters: [], + usage: '/clear', + scope: 'local', + action: (params = null) => { + // eslint-disable-line + this.props.clearActivities(); + }, + }, + ]; + } + + componentDidMount() { + if (!hasTouchSupport) { + // Disable for now due to vary issues: + // Paste not working, shift+enter line breaks + // autosize(this.textInput); + this.textInput.addEventListener('autosize:resized', () => { + this.props.scrollToBottom(); + }); + } + } + + componentWillReceiveProps(nextProps) { + if (nextProps.focusChat) { + if (!getSelectedText()) { + // Don't focus for now, evaluate UX benfits + // this.textInput.focus() + } + } + } + + componentDidUpdate(nextProps, nextState) { + if (!nextState.message.trim().length) { + // autosize.update(this.textInput) + } + } + + handleKeyUp(e) { + if (e.key === 'Shift') { + this.setState({ + shiftKeyDown: false, + }); + } + } + + handleKeyPress(e) { + if (e.key === 'Shift') { + this.setState({ + shiftKeyDown: true, + }); + } + // Fix when autosize is enabled - line breaks require shift+enter twice + if (e.key === 'Enter' && !hasTouchSupport && !this.state.shiftKeyDown) { + e.preventDefault(); + if (this.canSend()) { + this.sendMessage(); + } else { + this.setState({ + message: '', + }); + } + } + } + + executeCommand(command) { + const commandToExecute = this.commands.find(cmnd => cmnd.command === command.command); + + if (commandToExecute) { + const { params } = command; + const commandResult = commandToExecute.action(params); + + return commandResult; + } + + return null; + } + + handleSendClick() { + this.sendMessage.bind(this); + this.textInput.focus(); + } + + handleFormSubmit(evt) { + evt.preventDefault(); + this.sendMessage(); + } + + parseCommand(message) { + const commandTrigger = { + command: null, + params: [], + }; + + if (message.charAt(0) === '/') { + const parsedCommand = message.replace('/', '').split(' '); + commandTrigger.command = sanitizeHtml(parsedCommand[0]) || null; + // Get params + if (parsedCommand.length >= 2) { + for (let i = 1; i < parsedCommand.length; i++) { + commandTrigger.params.push(parsedCommand[i]); + } + } + + return commandTrigger; + } + + return false; + } + + sendMessage() { + if (!this.canSend()) { + return; + } + + const { message } = this.state; + const isCommand = this.parseCommand(message); + + if (isCommand) { + const res = this.executeCommand(isCommand); + if (res === false) { + return; + } + } else { + this.props.sendEncryptedMessage({ + type: 'TEXT_MESSAGE', + payload: { + text: message, + timestamp: Date.now(), + }, + }); + } + + this.setState({ + message: '', + }); + } + + handleInputChange(evt) { + this.setState({ + message: evt.target.value, + }); + } + + canSend() { + return this.state.message.trim().length; + } + + render() { + const touchSupport = this.state.touchSupport; + + return ( +
+