Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Use binary IPC for Ensu attachments

Manav Rathi31f67ae8aa65
diff --git a/rust/apps/ensu/src-tauri/src/commands/crypto.rs b/rust/apps/ensu/src-tauri/src/commands/crypto.rs
index 1392b48bb6..8dbb3f6c29 100644
--- a/rust/apps/ensu/src-tauri/src/commands/crypto.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/crypto.rs
@@ -1,7 +1,11 @@
use serde::{Deserialize, Serialize};
+use tauri::ipc::{InvokeBody, Request, Response};
use crate::commands::common::ApiError;
+const CHAT_KEY_HEADER: &str = "chat-key";
+const SESSION_UUID_HEADER: &str = "session-uuid";
+
impl From<ente_ensu_crypto::Error> for ApiError {
fn from(error: ente_ensu_crypto::Error) -> Self {
ApiError::new(error.code(), error.to_string())
@@ -46,14 +50,6 @@ pub struct FieldInput {
key_b64: String,
}
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AttachmentInput {
- data_b64: String,
- key_b64: String,
- session_uuid: String,
-}
-
#[tauri::command]
pub fn chat_crypto_generate_key() -> String {
ente_ensu_crypto::generate_chat_key()
@@ -85,13 +81,30 @@ pub fn chat_crypto_decrypt_field(input: FieldInput) -> Result<String, ApiError>
}
#[tauri::command]
-pub fn chat_crypto_encrypt_attachment(input: AttachmentInput) -> Result<String, ApiError> {
- ente_ensu_crypto::encrypt_attachment_b64(&input.data_b64, &input.key_b64, &input.session_uuid)
- .map_err(Into::into)
+pub fn chat_crypto_encrypt_attachment(request: Request<'_>) -> Result<Response, ApiError> {
+ transform_attachment(request, ente_ensu_crypto::encrypt_attachment)
}
#[tauri::command]
-pub fn chat_crypto_decrypt_attachment(input: AttachmentInput) -> Result<String, ApiError> {
- ente_ensu_crypto::decrypt_attachment_b64(&input.data_b64, &input.key_b64, &input.session_uuid)
+pub fn chat_crypto_decrypt_attachment(request: Request<'_>) -> Result<Response, ApiError> {
+ transform_attachment(request, ente_ensu_crypto::decrypt_attachment)
+}
+
+fn transform_attachment(
+ request: Request<'_>,
+ transform: impl FnOnce(&[u8], &str, &str) -> ente_ensu_crypto::Result<Vec<u8>>,
+) -> Result<Response, ApiError> {
+ let InvokeBody::Raw(data) = request.body() else {
+ return Err(ApiError::new("invalid_args", "Expected attachment bytes"));
+ };
+ let header = |name| {
+ request
+ .headers()
+ .get(name)
+ .and_then(|value| value.to_str().ok())
+ .ok_or_else(|| ApiError::new("invalid_args", format!("Missing {name} header")))
+ };
+ transform(data, header(CHAT_KEY_HEADER)?, header(SESSION_UUID_HEADER)?)
+ .map(Response::new)
.map_err(Into::into)
}
diff --git a/rust/crates/ensu-crypto/src/lib.rs b/rust/crates/ensu-crypto/src/lib.rs
index 2e11c36061..c8244531f1 100644
--- a/rust/crates/ensu-crypto/src/lib.rs
+++ b/rust/crates/ensu-crypto/src/lib.rs
@@ -88,30 +88,6 @@ pub fn decrypt_attachment(data: &[u8], chat_key_b64: &str, session_uuid: &str) -
decrypt_blob(data, attachment_key(chat_key_b64, session_uuid)?.as_bytes())
}
-pub fn encrypt_attachment_b64(
- data_b64: &str,
- chat_key_b64: &str,
- session_uuid: &str,
-) -> Result<String> {
- Ok(b64::encode(&encrypt_attachment(
- &b64::decode(data_b64)?,
- chat_key_b64,
- session_uuid,
- )?))
-}
-
-pub fn decrypt_attachment_b64(
- data_b64: &str,
- chat_key_b64: &str,
- session_uuid: &str,
-) -> Result<String> {
- Ok(b64::encode(&decrypt_attachment(
- &b64::decode(data_b64)?,
- chat_key_b64,
- session_uuid,
- )?))
-}
-
pub fn encrypt_blob(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>> {
Ok(blob::encrypt_combined(
plaintext,
diff --git a/web/apps/ensu/src/services/base64.ts b/web/apps/ensu/src/services/base64.ts
deleted file mode 100644
index bee7ed4c2f..0000000000
--- a/web/apps/ensu/src/services/base64.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export const bytesToBase64 = (bytes: Uint8Array): string => {
- const chunkSize = 0x8000;
- let binary = "";
- for (let i = 0; i < bytes.length; i += chunkSize) {
- const chunk = bytes.subarray(i, i + chunkSize);
- for (const value of chunk) {
- binary += String.fromCharCode(value);
- }
- }
- return btoa(binary);
-};
-
-export const base64ToBytes = (b64: string): Uint8Array<ArrayBuffer> => {
- const binary = atob(b64);
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++) {
- bytes[i] = binary.charCodeAt(i);
- }
- return bytes;
-};
diff --git a/web/apps/ensu/src/services/chat/compatibility.ts b/web/apps/ensu/src/services/chat/compatibility.ts
index 38c767fd7e..ba342560ce 100644
--- a/web/apps/ensu/src/services/chat/compatibility.ts
+++ b/web/apps/ensu/src/services/chat/compatibility.ts
@@ -1,4 +1,3 @@
-import { base64ToBytes } from "@/services/base64";
import { isTauriRuntime } from "@/services/tauri-runtime";
import { removeKV } from "ente-base/kv";
import log from "ente-base/log";
@@ -219,7 +218,9 @@ const localStorageStore = (): BrowserStore => {
parsed.messages ?? [],
(parsed.attachmentBytes ?? []).map(({ id, data }) => ({
id,
- data: base64ToBytes(data),
+ data: Uint8Array.from(atob(data), (value) =>
+ value.charCodeAt(0),
+ ),
})),
);
} catch (error) {
diff --git a/web/apps/ensu/src/services/chat/crypto.ts b/web/apps/ensu/src/services/chat/crypto.ts
index ebe3b61f8b..f79a3c6c5a 100644
--- a/web/apps/ensu/src/services/chat/crypto.ts
+++ b/web/apps/ensu/src/services/chat/crypto.ts
@@ -1,7 +1,7 @@
-import { base64ToBytes, bytesToBase64 } from "@/services/base64";
import { isTauriRuntime } from "@/services/tauri-runtime";
type EnsuWasmModule = typeof import("ente-ensu-wasm");
+type TauriCoreModule = typeof import("@tauri-apps/api/core");
export interface EncryptedChatPayload {
encryptedData: string;
@@ -11,11 +11,10 @@ export interface EncryptedChatPayload {
const ensuWasm = () => import("ente-ensu-wasm");
const tauriInvoke = async <T>(
- command: string,
- args?: Record<string, unknown>,
+ ...args: Parameters<TauriCoreModule["invoke"]>
) => {
const { invoke } = await import("@tauri-apps/api/core");
- return invoke<T>(command, args);
+ return invoke<T>(...args);
};
const encryptedChatPayloadValue = (
@@ -30,6 +29,18 @@ const encryptedChatPayloadValue = (
const wasmBytes = (bytes: Uint8Array) => bytes as Uint8Array<ArrayBuffer>;
+const invokeAttachmentCommand = async (
+ command: string,
+ data: Uint8Array,
+ chatKeyB64: string,
+ sessionUuid: string,
+) =>
+ new Uint8Array(
+ await tauriInvoke<ArrayBuffer>(command, data, {
+ headers: { "chat-key": chatKeyB64, "session-uuid": sessionUuid },
+ }),
+ );
+
export const generateChatKey = async () =>
isTauriRuntime()
? tauriInvoke<string>("chat_crypto_generate_key")
@@ -96,14 +107,11 @@ export const encryptAttachmentBytes = async (
sessionUuid: string,
): Promise<Uint8Array<ArrayBuffer>> =>
isTauriRuntime()
- ? base64ToBytes(
- await tauriInvoke<string>("chat_crypto_encrypt_attachment", {
- input: {
- dataB64: bytesToBase64(data),
- keyB64: chatKeyB64,
- sessionUuid,
- },
- }),
+ ? invokeAttachmentCommand(
+ "chat_crypto_encrypt_attachment",
+ data,
+ chatKeyB64,
+ sessionUuid,
)
: wasmBytes(
(await ensuWasm()).encryptChatAttachment(
@@ -119,14 +127,11 @@ export const decryptAttachmentBytes = async (
sessionUuid: string,
): Promise<Uint8Array<ArrayBuffer>> =>
isTauriRuntime()
- ? base64ToBytes(
- await tauriInvoke<string>("chat_crypto_decrypt_attachment", {
- input: {
- dataB64: bytesToBase64(data),
- keyB64: chatKeyB64,
- sessionUuid,
- },
- }),
+ ? invokeAttachmentCommand(
+ "chat_crypto_decrypt_attachment",
+ data,
+ chatKeyB64,
+ sessionUuid,
)
: wasmBytes(
(await ensuWasm()).decryptChatAttachment(