Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SK-267 added support for outdated session restore #136

Merged
merged 6 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ class Api {
return;
}

if (message.message_decryption_failed) {
if (this.onMessageDecryptionFailedListener) {
this.onMessageDecryptionFailedListener(
message.message_decryption_failed
);
}
return;
}

if (message.message) {
if (message.message.error) {
this.responsesPromises[
Expand Down Expand Up @@ -401,6 +410,21 @@ class Api {
return this.sendPromise(requestData, resObjKey);
}

async markDecrypionFailedMessages(data) {
const requestData = {
request: {
message_decryption_failed: {
cid: data.cid,
ids: data.mids,
},
id: getUniqueId("markDecrypionFailedMessages"),
},
};

const resObjKey = "success";
return this.sendPromise(requestData, resObjKey);
}

async messageDelete(data) {
//===============to do
const requestData = {
Expand Down
2 changes: 1 addition & 1 deletion src/assets/icons/_helpers/CornerAccent.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/assets/icons/_helpers/CornerDanger.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/assets/icons/status/DecryptionFailed.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion src/components/auth/components/LoginLinks.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ export default function LoginLinks({ changePage, content }) {
setIsLoader(true);
try {
const userData = await usersService.login(content);
await garbageCleaningService.resetDataOnAuth();
await encryptionService.registerDevice(userData._id);
navigateTo("/");
subscribeForNotifications();
await garbageCleaningService.resetDataOnAuth();
dispatch(setCurrentUserId(userData._id));
dispatch(upsertUser(userData));
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/auth/components/SignUpLinks.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export default function SignUpLinks({ changePage, content }) {

if (isLogin) {
const userData = await usersService.login(content);
await garbageCleaningService.resetDataOnAuth();
await encryptionService.registerDevice(userData._id);
subscribeForNotifications();
await garbageCleaningService.resetDataOnAuth();
dispatch(upsertUser(userData));
dispatch(setCurrentUserId(userData._id));
}
Expand Down
31 changes: 22 additions & 9 deletions src/components/hub/elements/ChatMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import MessageAttachments from "@components/message/elements/MessageAttachments"
import MessageStatus from "@components/message/elements/MessageStatus";
import MessageUserIcon from "@components/hub/elements/MessageUserIcon";
import addSuffix from "@utils/navigation/add_suffix";
import encryptionService from "@services/encryptionService";
import getUserFullName from "@utils/user/get_user_full_name";
import { urlify } from "@utils/text/urlify";
import { useLocation } from "react-router-dom";
Expand All @@ -11,6 +12,7 @@ import "@styles/hub/elements/ChatMessage.css";

import { ReactComponent as CornerLight } from "@icons/_helpers/CornerLight.svg";
import { ReactComponent as CornerAccent } from "@icons/_helpers/CornerAccent.svg";
import { ReactComponent as CornerDanger } from "@icons/_helpers/CornerDanger.svg";

export default function ChatMessage({
sender,
Expand All @@ -23,6 +25,7 @@ export default function ChatMessage({

const { body, from, attachments, status, t } = message;
const isCurrentUser = from === currentUserId;
const isError = status === "decryption_failed";

const timeSend = useMemo(() => {
const time = new Date(t * 1000);
Expand All @@ -36,9 +39,14 @@ export default function ChatMessage({

return (
<div
className={`message__container${isCurrentUser ? "--my" : ""} ${
prev ? "" : "mt-8"
}`}
className={`message__container${isCurrentUser ? "--my" : ""}${
isError ? " danger" : ""
}${prev ? "" : " mt-8"}`}
onClick={
isError
? () => encryptionService.createNewSessionAndSendMessage(message)
: undefined
}
>
<div className={`message-photo${sender ? "--hover" : ""}`}>
{next ? null : (
Expand All @@ -50,12 +58,17 @@ export default function ChatMessage({
</div>
)}
</div>
<div className={`message-content__container ${next ? "" : "br-bl-0"}`}>
{next ? null : isCurrentUser ? (
<CornerAccent className="message-content--corner" />
) : (
<CornerLight className="message-content--corner" />
)}
<div className={`message-content__container${next ? "" : " br-bl-0"}`}>
{!next &&
(isCurrentUser ? (
isError ? (
<CornerDanger className="message-content--corner" />
) : (
<CornerAccent className="message-content--corner" />
)
) : (
<CornerLight className="message-content--corner" />
))}
{prev ? null : (
<div
className={`content__uname${sender ? "--hover" : ""}`}
Expand Down
9 changes: 8 additions & 1 deletion src/components/message/elements/MessageStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,22 @@ import { ReactComponent as Sent } from "@icons/status/Sent.svg";
import { ReactComponent as ReadWhite } from "@icons/status/ReadWhite.svg";
import { ReactComponent as SendingWhite } from "@icons/status/SendingWhite.svg";
import { ReactComponent as SentWhite } from "@icons/status/SentWhite.svg";
import { ReactComponent as DecryptionFailed } from "@icons/status/DecryptionFailed.svg";

export default function MessageStatus({ status, type }) {
const iconColor = type === "white" ? "white" : "accent";

const iconMap = {
accent: { sent: <Sent />, read: <Read />, default: <Sending /> },
accent: {
sent: <Sent />,
read: <Read />,
decryption_failed: <DecryptionFailed />,
default: <Sending />,
},
white: {
sent: <SentWhite />,
read: <ReadWhite />,
decryption_failed: <DecryptionFailed />,
default: <SendingWhite />,
},
};
Expand Down
9 changes: 9 additions & 0 deletions src/services/conversationsService.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import DownloadManager from "@src/adapters/downloadManager";
import api from "@api/api";
import eventEmitter from "@event/eventEmitter";
import isEqualsNativeIds from "@utils/user/isEqualsNativeIds";
import isHeic from "@utils/media/is_heic";
import navigateTo from "@utils/navigation/navigate_to";
import processFile from "@utils/media/process_file";
Expand Down Expand Up @@ -294,6 +295,14 @@ class ConversationsService {
async getParticipantsByIds(params) {
return await api.getUsersByIds(params);
}

findOpponentIdForPrivateConversationByCid(cid, currentUserId) {
const conversation = store.getState().conversations.entities[cid];

return isEqualsNativeIds(conversation.owner_id, currentUserId)
? conversation.opponent_id
: conversation.owner_id;
}
}

const conversationService = new ConversationsService();
Expand Down
45 changes: 42 additions & 3 deletions src/services/encryptionService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import CryptoJS from "crypto-js";
import api from "@api/api";
import indexedDB from "@store/indexedDB";
import initVodozemac, {
Account,
OlmMessage,
Expand All @@ -10,11 +11,14 @@ import store from "@store/store";
import { decodeBase64, encodeUnpaddedBase64 } from "@utils/base64/base64";
import { upsertMessage } from "@store/values/Messages";
import { upsertUser } from "@store/values/Participants";
import conversationService from "./conversationsService";
import messagesService from "./messagesService";

class EncryptionService {
#encryptionSessions = {};
#account = null;
#vodozemacInitialized = false;
visibleBody = "Can`t decrypt this message, not for this device";

constructor() {
this.#initializeVodozemac();
Expand All @@ -30,6 +34,10 @@ class EncryptionService {
}
}

markDecrypionFailedMessages(cid, mids) {
api.markDecrypionFailedMessages({ cid, mids });
}

hasAccount() {
return !!this.#account;
}
Expand All @@ -44,6 +52,11 @@ class EncryptionService {
await localforage.clear();
}

async clearStoredSessionWithUser(userId) {
delete this.#encryptionSessions[userId];
await localforage.removeItem(`encryptedSession${userId}`);
}

encryptMessage(text, userId) {
const session = this.#encryptionSessions[userId];
return session.encrypt(text);
Expand All @@ -61,14 +74,18 @@ class EncryptionService {
console.log(
"[encryption] Encrypted session with the opponent is missing"
);
return "Can`t decrypt this message, not for this device";
return this.visibleBody;
}

try {
return session.decrypt(olmMessage);
} catch (error) {
console.log("[encryption] Failed to decrypt an encrypted message", error);
return "Can`t decrypt this message, not for this device";
this.markDecrypionFailedMessages(olmMessageParams.cid, [
olmMessageParams._id,
]);

return this.visibleBody;
}
}

Expand Down Expand Up @@ -274,6 +291,7 @@ class EncryptionService {
console.log("Encrypted session from local store:", session);
const decryptMessage = this.decryptMessage(olmMessageParams, userId);

indexedDB.upsertEncryptionMessage(olmMessageParams._id, decryptMessage);
store.dispatch(
upsertMessage({ _id: olmMessageParams._id, body: decryptMessage })
);
Expand Down Expand Up @@ -319,20 +337,26 @@ class EncryptionService {
if (olmMessage) {
console.log("Create session with olmMessage: ", olmMessage);

let decryptMessage = this.visibleBody;
try {
const inboundSession = this.#account.create_inbound_session(
userKeys.identity_key,
olmMessage
);
const decryptMessage = `${inboundSession.plaintext}`;
decryptMessage = `${inboundSession.plaintext}`;
session = inboundSession.session;

store.dispatch(
upsertMessage({ _id: olmMessageParams._id, body: decryptMessage })
);
} catch (error) {
this.markDecrypionFailedMessages(olmMessageParams.cid, [
olmMessageParams._id,
]);

console.error("Failed to create inbound session:", error);
}
indexedDB.upsertEncryptionMessage(olmMessageParams._id, decryptMessage);

//check if the top block worked successfully -> mb need to clear the session param
if (session) {
Expand Down Expand Up @@ -361,6 +385,21 @@ class EncryptionService {
}
}

async createNewSessionAndSendMessage(message) {
console.log("[encryption] Recreate a new encrypted session");
const messageParams = Object.assign({}, message);
const { _id: mid, cid, from } = messageParams;
const opponentId =
conversationService.findOpponentIdForPrivateConversationByCid(cid, from);

await this.clearStoredSessionWithUser(opponentId);
await this.createEncryptionSession(opponentId);

await messagesService.removeMessageFromLocalStore(mid, cid);

await messagesService.sendEncryptedMessage(messageParams, opponentId);
}

async encrypteDataForLocalStore(data) {
const secretKey = await this.#getPickleKey(
"pickleKey",
Expand Down
2 changes: 1 addition & 1 deletion src/services/garbageCleaningService.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import { updateNetworkState } from "@store/values/NetworkState";
class GarbageCleaningService {
async clearConversationMessages(cid) {
if (!cid) return;
store.dispatch(clearMessagesToLocalLimit(cid));
store.dispatch(clearMessageIdsToLocalLimit(cid));
store.dispatch(clearMessagesToLocalLimit(cid));
}

async resetDataOnAuth() {
Expand Down
Loading