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

Add support for sending encrypted to_device #101

Merged
merged 20 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# UNRELEASED

- Adds a new API `Device#encryptToDeviceEvent` to encrypt a to-device event using
Olm.

# matrix-sdk-crypto-wasm v4.6.0

- Update dependencies, including matrix-rust-sdk to
Expand Down
41 changes: 40 additions & 1 deletion src/device.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
//! Types for a `Device`.

use js_sys::{Array, Map, Promise};
use serde::Serialize;
use serde_json::Value;
use serde_wasm_bindgen::Serializer;
use wasm_bindgen::prelude::*;

use crate::{
encryption::EncryptionAlgorithm,
future::future_to_promise,
identifiers::{self, DeviceId, UserId},
impl_from_to_inner, requests, types, verification, vodozemac,
impl_from_to_inner,
requests::{self},
richvdh marked this conversation as resolved.
Show resolved Hide resolved
types, verification, vodozemac,
};

/// A device represents a E2EE capable client of an user.
Expand Down Expand Up @@ -51,6 +56,40 @@ impl Device {
}))
}

/// Encrypt a to-device message to be sent to this device, using Olm
/// encryption.
///
/// Prior to calling this method you must ensure that an olm session is
richvdh marked this conversation as resolved.
Show resolved Hide resolved
/// available for the target device. This can be done by calling
/// {@link OlmMachine.getMissingSessions}.
///
/// The caller is responsible for sending the encrypted
/// event to the target device. If multiple messages are
/// encrypted for the same device using this method they should be sent in
/// the same order as they are encrypted.
///
/// # Returns
/// Returns a Promise for a js object of the encrypted event.
richvdh marked this conversation as resolved.
Show resolved Hide resolved
/// Can be used to create the payload for a `/sendToDevice` API.
#[wasm_bindgen(js_name = "encryptToDeviceEvent")]
pub fn encrypt_to_device_event(
&self,
event_type: String,
content: JsValue,
) -> Result<Promise, JsError> {
let me = self.inner.clone();
let content: Value = serde_wasm_bindgen::from_value(content)?;
let event_type = event_type.clone();
richvdh marked this conversation as resolved.
Show resolved Hide resolved

Ok(future_to_promise(async move {
let raw_encrypted = me.encrypt_event_raw(event_type.as_str(), &content).await?;

let to_device_encrypted = raw_encrypted.deserialize()?;
// Using json_compatible() to convert into plain object instead of Map.
Ok(to_device_encrypted.serialize(&Serializer::json_compatible()).unwrap())
}))
}

/// Is this device considered to be verified.
///
/// This method returns true if either the `is_locally_trusted`
Expand Down
82 changes: 82 additions & 0 deletions tests/device.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,88 @@ describe(OlmMachine.name, () => {
});
});

describe("Send to-device message", () => {
const userId1 = new UserId("@alice:example.org");
const deviceId1 = new DeviceId("alice_device");

function machine(newUser, newDevice) {
return OlmMachine.initialize(newUser, newDevice);
}

it("can encrypt a to-device message", async () => {
// Olm machine.
const m = await machine(userId1, deviceId1);

// Make m aware of another device, and get some OTK to be able to establish a session.
await m.markRequestAsSent(
"foo",
RequestType.KeysQuery,
JSON.stringify({
device_keys: {
"@example:localhost": {
AFGUOBTZWM: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "AFGUOBTZWM",
keys: {
"curve25519:AFGUOBTZWM": "boYjDpaC+7NkECQEeMh5dC+I1+AfriX0VXG2UV7EUQo",
"ed25519:AFGUOBTZWM": "NayrMQ33ObqMRqz6R9GosmHdT6HQ6b/RX/3QlZ2yiec",
},
signatures: {
"@example:localhost": {
"ed25519:AFGUOBTZWM":
"RoSWvru1jj6fs2arnTedWsyIyBmKHMdOu7r9gDi0BZ61h9SbCK2zLXzuJ9ZFLao2VvA0yEd7CASCmDHDLYpXCA",
},
},
user_id: "@example:localhost",
unsigned: {
device_display_name: "rust-sdk",
},
},
},
},
failures: {},
}),
);

await m.markRequestAsSent(
"bar",
RequestType.KeysClaim,
JSON.stringify({
one_time_keys: {
"@example:localhost": {
AFGUOBTZWM: {
"signed_curve25519:AAAABQ": {
key: "9IGouMnkB6c6HOd4xUsNv4i3Dulb4IS96TzDordzOws",
signatures: {
"@example:localhost": {
"ed25519:AFGUOBTZWM":
"2bvUbbmJegrV0eVP/vcJKuIWC3kud+V8+C0dZtg4dVovOSJdTP/iF36tQn2bh5+rb9xLlSeztXBdhy4c+LiOAg",
},
},
},
},
},
},
failures: {},
}),
);

// Pick the device we want to encrypt to.
const device2 = await m.getDevice(new UserId("@example:localhost"), new DeviceId("AFGUOBTZWM"));

const content = {
body: "Hello, World!",
};
const type = "some.custom.event.type";

const toDevice = await device2.encryptToDeviceEvent(type, content);

expect(toDevice.algorithm).toStrictEqual("m.olm.v1.curve25519-aes-sha2");
expect(toDevice.ciphertext).toBeDefined();
expect(toDevice.ciphertext["boYjDpaC+7NkECQEeMh5dC+I1+AfriX0VXG2UV7EUQo"]).toBeDefined();
});
});

describe("Key Verification", () => {
const userId1 = new UserId("@alice:example.org");
const deviceId1 = new DeviceId("alice_device");
Expand Down
Loading