refactor: deduplicate encryption helpers (#4146)

This commit is contained in:
David Luzar 2021-11-07 14:33:21 +01:00 committed by GitHub
parent f59e608f18
commit 6143d5195a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 84 additions and 148 deletions

View file

@ -24,7 +24,6 @@ import {
SYNC_FULL_SCENE_INTERVAL_MS,
} from "../app_constants";
import {
decryptAESGEM,
generateCollaborationLinkData,
getCollaborationLink,
SocketUpdateDataSource,
@ -65,6 +64,7 @@ import {
ReconciledElements,
reconcileElements as _reconcileElements,
} from "./reconciliation";
import { decryptData } from "../../data/encryption";
interface CollabState {
modalIsShown: boolean;
@ -301,6 +301,27 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
return await this.fileManager.getFiles(unfetchedImages);
};
private decryptPayload = async (
iv: Uint8Array,
encryptedData: ArrayBuffer,
decryptionKey: string,
) => {
try {
const decrypted = await decryptData(iv, encryptedData, decryptionKey);
const decodedData = new TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
return JSON.parse(decodedData);
} catch (error) {
window.alert(t("alerts.decryptFailed"));
console.error(error);
return {
type: "INVALID_RESPONSE",
};
}
};
private initializeSocketClient = async (
existingRoomLinkData: null | { roomId: string; roomKey: string },
): Promise<ImportedDataState | null> => {
@ -388,10 +409,11 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
if (!this.portal.roomKey) {
return;
}
const decryptedData = await decryptAESGEM(
const decryptedData = await this.decryptPayload(
iv,
encryptedData,
this.portal.roomKey,
iv,
);
switch (decryptedData.type) {

View file

@ -1,8 +1,4 @@
import {
encryptAESGEM,
SocketUpdateData,
SocketUpdateDataSource,
} from "../data";
import { SocketUpdateData, SocketUpdateDataSource } from "../data";
import CollabWrapper from "./CollabWrapper";
@ -13,6 +9,7 @@ import { trackEvent } from "../../analytics";
import { throttle } from "lodash";
import { newElementWith } from "../../element/mutateElement";
import { BroadcastedExcalidrawElement } from "./reconciliation";
import { encryptData } from "../../data/encryption";
class Portal {
collab: CollabWrapper;
@ -79,12 +76,13 @@ class Portal {
if (this.isOpen()) {
const json = JSON.stringify(data);
const encoded = new TextEncoder().encode(json);
const encrypted = await encryptAESGEM(encoded, this.roomKey!);
const { encryptedBuffer, iv } = await encryptData(this.roomKey!, encoded);
this.socket?.emit(
volatile ? BROADCAST.SERVER_VOLATILE : BROADCAST.SERVER,
this.roomId,
encrypted.data,
encrypted.iv,
encryptedBuffer,
iv,
);
}
}