11 Commits

Author SHA1 Message Date
Sharon Kennedy
46868b141a 1.1.0 2020-06-11 23:03:05 -04:00
Sharon Kennedy
247bc3e2ba 1.1.1 2020-06-11 23:02:14 -04:00
Sharon Kennedy
29b86e4190 1.1.0 2020-06-11 23:02:03 -04:00
Sharon Kennedy
716f61b183 1.1.1 2020-06-11 23:01:43 -04:00
Sharon Kennedy
516a1e0fbd encrypt by default 2020-06-11 22:59:42 -04:00
Sharon Kennedy
80ecf98be1 1.1.0 2020-06-11 11:01:52 -04:00
Sharon Kennedy
f0b43743f7 add flag to disable encryption 2020-06-11 08:31:46 -04:00
Sharon Kennedy
5252321f56 store messages in object instead of array 2020-06-11 01:54:05 -04:00
Sharon Kennedy
93135daaa8 close chat connection if chat is offline 2020-06-10 17:49:19 -04:00
Sharon Kennedy
f27ebb3c71 move offline messaging to chatbox instead of bot 2020-06-10 16:59:50 -04:00
Sharon Kennedy
7d5ad29b60 use rhok server for demo 2020-05-27 22:22:16 -04:00
4 changed files with 119 additions and 74 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "private-safesupport-chatbox", "name": "private-safesupport-chatbox",
"version": "1.0.2", "version": "1.1.0",
"description": "A secure and private embeddable chatbox that connects to Riot", "description": "A secure and private embeddable chatbox that connects to Riot",
"main": "dist/chatbox.js", "main": "dist/chatbox.js",
"scripts": { "scripts": {

View File

@@ -13,8 +13,8 @@
<script src="./chatbox.js"></script> <script src="./chatbox.js"></script>
<script> <script>
var config = { var config = {
matrixServerUrl: 'https://matrix.safesupport.chat', matrixServerUrl: 'https://matrix.rhok.space',
botId: '@help-bot:safesupport.chat', botId: '@help-bot:rhok.space',
roomName: 'Support Chat', roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/', termsUrl: 'https://tosdr.org/',
introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.", introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.",

View File

@@ -25,7 +25,7 @@ const ENCRYPTION_NOTICE = "Messages in this chat are secured with end-to-end enc
const UNENCRYPTION_NOTICE = "Messages in this chat are not encrypted." const UNENCRYPTION_NOTICE = "Messages in this chat are not encrypted."
const RESTARTING_UNENCRYPTED_CHAT_MESSAGE = "Restarting chat without encryption." const RESTARTING_UNENCRYPTED_CHAT_MESSAGE = "Restarting chat without encryption."
const WAIT_TIME_MS = 120000 // 2 minutes const WAIT_TIME_MS = 120000 // 2 minutes
const CHAT_IS_OFFLINE_NOTICE = "Chat is offline" const CHAT_IS_OFFLINE_NOTICE = "CHAT_OFFLINE"
const DEFAULT_MATRIX_SERVER = "https://matrix.rhok.space/" const DEFAULT_MATRIX_SERVER = "https://matrix.rhok.space/"
const DEFAULT_BOT_ID = "@help-bot:rhok.space" const DEFAULT_BOT_ID = "@help-bot:rhok.space"
@@ -37,7 +37,9 @@ const DEFAULT_CONFIRMATION_MESSAGE = "Waiting for a facilitator to join the chat
const DEFAULT_EXIT_MESSAGE = "The chat is closed. You may close this window." const DEFAULT_EXIT_MESSAGE = "The chat is closed. You may close this window."
const DEFAULT_ANONYMOUS_DISPLAY_NAME="Anonymous" const DEFAULT_ANONYMOUS_DISPLAY_NAME="Anonymous"
const DEFAULT_CHAT_UNAVAILABLE_MESSAGE = "The chat service is not available right now. Please try again later." const DEFAULT_CHAT_UNAVAILABLE_MESSAGE = "The chat service is not available right now. Please try again later."
const DEFAULT_CHAT_OFFLINE_MESSAGE = "There are no facilitators currently available. For immediate service, please call 123-456-7890."
const DEFAULT_WAIT_MESSAGE = "Please be patient, our online facilitators are currently responding to other support requests." const DEFAULT_WAIT_MESSAGE = "Please be patient, our online facilitators are currently responding to other support requests."
const DEFAULT_ENCRYPTION_DISABLED = false
class ChatBox extends React.Component { class ChatBox extends React.Component {
@@ -52,7 +54,7 @@ class ChatBox extends React.Component {
userId: null, userId: null,
password: null, password: null,
localStorage: null, localStorage: null,
messages: [], messages: {},
inputValue: "", inputValue: "",
errors: [], errors: [],
roomId: null, roomId: null,
@@ -144,27 +146,31 @@ class ChatBox extends React.Component {
} }
} }
exitChat = async () => { exitChat = async (resetState=true) => {
if (!this.state.client) return null; if (this.state.client) {
await this.state.client.leave(this.state.roomId)
await this.state.client.leave(this.state.roomId) const auth = {
type: 'm.login.password',
user: this.state.userId,
identifier: {
type: "m.id.user",
user: this.state.userId,
},
password: this.state.password,
};
const auth = { await this.state.client.deactivateAccount(auth, true)
type: 'm.login.password', await this.state.client.stopClient()
user: this.state.userId, await this.state.client.clearStores()
identifier: { this.setState({ client: null })
type: "m.id.user", }
user: this.state.userId,
},
password: this.state.password,
};
await this.state.client.deactivateAccount(auth, true)
await this.state.client.stopClient()
await this.state.client.clearStores()
this.state.localStorage.clear() this.state.localStorage.clear()
this.setState(this.initialState)
if (resetState) {
this.setState(this.initialState)
}
} }
createLocalStorage = async (deviceId, sessionId) => { createLocalStorage = async (deviceId, sessionId) => {
@@ -232,14 +238,14 @@ class ChatBox extends React.Component {
try { try {
await client.initCrypto() await client.initCrypto()
} catch(err) { } catch(err) {
return this.initializeUnencryptedChat() return this.restartWithoutCrypto()
} }
await client.startClient() await client.startClient()
await this.createRoom(client) await this.createRoom(client)
} }
initializeUnencryptedChat = async () => { restartWithoutCrypto = async () => {
if (this.state.client) { if (this.state.client) {
this.state.client.leave(this.state.roomId) this.state.client.leave(this.state.roomId)
this.state.client.stopClient() this.state.client.stopClient()
@@ -282,7 +288,21 @@ class ChatBox extends React.Component {
console.log("error", err) console.log("error", err)
this.handleInitError(err) this.handleInitError(err)
} }
}
initializeUnencryptedChat = async () => {
this.setState({ ready: false })
const client = await this.createClientWithAccount()
this.setState({
client: client
})
client.setDisplayName(this.props.anonymousDisplayName)
this.setMatrixListeners(client)
await client.startClient()
await this.createRoom(client)
} }
handleInitError = (err) => { handleInitError = (err) => {
@@ -292,17 +312,8 @@ class ChatBox extends React.Component {
} }
handleDecryptionError = async (event, err) => { handleDecryptionError = async (event, err) => {
if (this.state.client) {
const isCryptoEnabled = await this.state.client.isCryptoEnabled()
const isRoomEncrypted = this.state.client.isRoomEncrypted(this.state.roomId)
if (!isCryptoEnabled || !isRoomEncrypted) {
return this.initializeUnencryptedChat()
}
}
const eventId = event.getId() const eventId = event.getId()
this.displayFakeMessage({ body: '** Unable to decrypt message **' }, event.getSender(), eventId) this.handleMessageEvent(event)
this.setState({ decryptionErrors: { [eventId]: true }}) this.setState({ decryptionErrors: { [eventId]: true }})
} }
@@ -376,31 +387,39 @@ class ChatBox extends React.Component {
} }
displayFakeMessage = (content, sender, messageId=uuid()) => { displayFakeMessage = (content, sender, messageId=uuid()) => {
const msgList = [...this.state.messages]
const msg = { const msg = {
id: messageId, id: messageId,
type: 'm.room.message', type: 'm.room.message',
sender: sender, sender: sender,
roomId: this.state.roomId, roomId: this.state.roomId,
content: content, content: content,
timestamp: Date.now(),
} }
msgList.push(msg)
this.setState({ messages: msgList }) this.setState({
messages: {
...this.state.messages,
[messageId]: msg
}
})
} }
displayBotMessage = (content, roomId) => { displayBotMessage = (content, roomId, messageId=uuid()) => {
const msgList = [...this.state.messages]
const msg = { const msg = {
id: uuid(), id: messageId,
type: 'm.room.message', type: 'm.room.message',
sender: this.props.botId, sender: this.props.botId,
roomId: roomId || this.state.roomId, roomId: roomId || this.state.roomId,
content: content, content: content,
timestamp: Date.now(),
} }
msgList.push(msg)
this.setState({ messages: msgList }) this.setState({
messages: {
...this.state.messages,
[messageId]: msg
}
})
} }
handleMessageEvent = event => { handleMessageEvent = event => {
@@ -410,8 +429,12 @@ class ChatBox extends React.Component {
sender: event.getSender(), sender: event.getSender(),
roomId: event.getRoomId(), roomId: event.getRoomId(),
content: event.getContent(), content: event.getContent(),
timestamp: event.getTs(),
} }
// there's also event.getClearContent() which only works on encrypted messages
// but not really sure when it should be used vs event.getContent()
if (message.content.showToUser && message.content.showToUser !== this.state.userId) { if (message.content.showToUser && message.content.showToUser !== this.state.userId) {
return; return;
} }
@@ -427,22 +450,41 @@ class ChatBox extends React.Component {
this.setState({ messagesInFlight }) this.setState({ messagesInFlight })
} }
// check for decryption error message and replace with decrypted message
// or push message to messages array
const messages = [...this.state.messages]
const decryptionErrors = {...this.state.decryptionErrors} const decryptionErrors = {...this.state.decryptionErrors}
delete decryptionErrors[message.id] delete decryptionErrors[message.id]
const existingMessageIndex = messages.findIndex(({ id }) => id === message.id)
if (existingMessageIndex > -1) { const isOfflineNotice = message.content.msgtype === "m.notice" && message.content.body === CHAT_IS_OFFLINE_NOTICE
messages.splice(existingMessageIndex, 1, message)
} else { let newMessage = message
messages.push(message)
// when the bot sends a notice that the chat is offline
// replace the message with the client-configured message
// for now we're treating m.notice and m.text messages the same
if (isOfflineNotice) {
newMessage = {
...message,
content: {
...message.content,
body: this.props.chatOfflineMessage
}
}
this.handleChatOffline(event.getRoomId())
} }
this.setState({ messages, decryptionErrors }) this.setState({
messages: {
...this.state.messages,
[message.id]: newMessage,
},
decryptionErrors
})
} }
handleChatOffline = (roomId) => {
this.exitChat(false) // close the chat connection but keep chatbox state
window.clearInterval(this.state.timeoutId) // no more waiting messages
this.setState({ ready: true }) // no more loading animation
}
handleKeyDown = (e) => { handleKeyDown = (e) => {
switch (e.keyCode) { switch (e.keyCode) {
@@ -492,12 +534,6 @@ class ChatBox extends React.Component {
return this.handleDecryptionError(event, err) return this.handleDecryptionError(event, err)
} }
if (event.getType() === "m.room.message") { if (event.getType() === "m.room.message") {
const content = event.getContent()
if (content.msgtype === "m.notice" && content.body === CHAT_IS_OFFLINE_NOTICE) {
this.setState({ ready: true })
return window.clearInterval(this.state.timeoutId)
}
this.handleMessageEvent(event) this.handleMessageEvent(event)
} }
}); });
@@ -513,7 +549,7 @@ class ChatBox extends React.Component {
} }
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
if (prevState.messages.length !== this.state.messages.length) { if ((prevState.messages !== this.state.messages) || (prevState.messagesInFlight !== this.state.messagesInFlight) || (prevState.typingStatus !== this.state.typingStatus)) {
if (this.messageWindow.current.scrollTo) { if (this.messageWindow.current.scrollTo) {
this.messageWindow.current.scrollTo(0, this.messageWindow.current.scrollHeight) this.messageWindow.current.scrollTo(0, this.messageWindow.current.scrollHeight)
} }
@@ -549,7 +585,11 @@ class ChatBox extends React.Component {
this.setState({ awaitingAgreement: false }) this.setState({ awaitingAgreement: false })
this.startWaitTimeForFacilitator() this.startWaitTimeForFacilitator()
try { try {
this.initializeChat() if (this.props.isEncryptionDisabled) {
this.initializeUnencryptedChat()
} else {
this.initializeChat()
}
} catch(err) { } catch(err) {
this.handleInitError(err) this.handleInitError(err)
} }
@@ -557,7 +597,7 @@ class ChatBox extends React.Component {
startWaitTimeForFacilitator = () => { startWaitTimeForFacilitator = () => {
const timeoutId = window.setInterval(() => { const timeoutId = window.setInterval(() => {
if (!this.state.facilitatorId) { if (!this.state.facilitatorId && !this.state.ready) {
this.displayBotMessage({ body: this.props.waitMessage }) this.displayBotMessage({ body: this.props.waitMessage })
} }
}, WAIT_TIME_MS) }, WAIT_TIME_MS)
@@ -575,7 +615,7 @@ class ChatBox extends React.Component {
const message = this.state.inputValue const message = this.state.inputValue
if (!Boolean(message)) return null; if (!Boolean(message)) return null;
if (this.state.isCryptoEnabled && !(this.state.client.isRoomEncrypted(this.state.roomId) && this.state.client.isCryptoEnabled())) return null; if (this.state.isCryptoEnabled && this.state.client && !(this.state.client.isRoomEncrypted(this.state.roomId) && this.state.client.isCryptoEnabled())) return null;
if (this.state.client && this.state.roomId) { if (this.state.client && this.state.roomId) {
const messagesInFlight = [...this.state.messagesInFlight] const messagesInFlight = [...this.state.messagesInFlight]
@@ -596,6 +636,7 @@ class ChatBox extends React.Component {
render() { render() {
const { ready, messages, messagesInFlight, inputValue, userId, roomId, typingStatus, opened, showDock, emojiSelectorOpen, isMobile, decryptionErrors } = this.state; const { ready, messages, messagesInFlight, inputValue, userId, roomId, typingStatus, opened, showDock, emojiSelectorOpen, isMobile, decryptionErrors } = this.state;
const orderedMessages = Object.values(messages).sort((a,b) => a.timestamp - b.timestamp)
const inputLabel = 'Send a message...' const inputLabel = 'Send a message...'
return ( return (
@@ -631,7 +672,7 @@ class ChatBox extends React.Component {
</div> </div>
{ {
messages.map((message, index) => { orderedMessages.map((message, index) => {
return( return(
<Message key={message.id} message={message} userId={userId} botId={this.props.botId} client={this.state.client} /> <Message key={message.id} message={message} userId={userId} botId={this.props.botId} client={this.state.client} />
) )
@@ -656,7 +697,7 @@ class ChatBox extends React.Component {
<div className={`message from-bot`}> <div className={`message from-bot`}>
<div className="text buttons"> <div className="text buttons">
{`Restart chat without encryption?`} {`Restart chat without encryption?`}
<button className="btn" id="accept" onClick={this.initializeUnencryptedChat}>RESTART</button> <button className="btn" id="accept" onClick={this.restartWithoutCrypto}>RESTART</button>
</div> </div>
</div> </div>
} }
@@ -715,6 +756,8 @@ ChatBox.propTypes = {
chatUnavailableMessage: PropTypes.string, chatUnavailableMessage: PropTypes.string,
anonymousDisplayName: PropTypes.string, anonymousDisplayName: PropTypes.string,
waitMessage: PropTypes.string, waitMessage: PropTypes.string,
chatOfflineMessage: PropTypes.string,
isEncryptionDisabled: PropTypes.bool,
} }
ChatBox.defaultProps = { ChatBox.defaultProps = {
@@ -729,6 +772,8 @@ ChatBox.defaultProps = {
anonymousDisplayName: DEFAULT_ANONYMOUS_DISPLAY_NAME, anonymousDisplayName: DEFAULT_ANONYMOUS_DISPLAY_NAME,
chatUnavailableMessage: DEFAULT_CHAT_UNAVAILABLE_MESSAGE, chatUnavailableMessage: DEFAULT_CHAT_UNAVAILABLE_MESSAGE,
waitMessage: DEFAULT_WAIT_MESSAGE, waitMessage: DEFAULT_WAIT_MESSAGE,
chatOfflineMessage: DEFAULT_CHAT_OFFLINE_MESSAGE,
isEncryptionDisabled: DEFAULT_ENCRYPTION_DISABLED
} }
export default ChatBox; export default ChatBox;

View File

@@ -1,17 +1,17 @@
import EmbeddableChatbox from './embeddable-chatbox'; import EmbeddableChatbox from './embeddable-chatbox';
const config = { const config = {
matrixServerUrl: 'https://matrix.safesupport.chat', matrixServerUrl: 'https://matrix.rhok.space',
botId: '@help-bot:safesupport.chat', botId: '@help-bot:rhok.space',
roomName: 'Support Chat', roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/', termsUrl: 'https://tosdr.org/',
introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.", introMessage: 'This chat application does not collect any of your personal data or any data from your use of this service.',
agreementMessage: 'Do you want to continue?', agreementMessage: 'Do you want to continue?',
confirmationMessage: 'Waiting for a facilitator to join the chat...', confirmationMessage: 'Waiting for a facilitator to join the chat...',
exitMessage: 'The chat is closed. You may close this window.', exitMessage: 'The chat is closed. You may close this window.',
chatUnavailableMessage: 'The chat service is not available right now. Please try again later.', chatUnavailableMessage: 'The chat service is not available right now. Please try again later.',
anonymousDisplayName: 'Anonymous', anonymousDisplayName: 'Anonymous',
} };
export default function bookmarklet() { export default function bookmarklet() {
if (window.EmbeddableChatbox) { if (window.EmbeddableChatbox) {