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 all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
- Fix `UserIdentity.isVerified` to take into account our own identity
[#d8d9dae](https://github.com/matrix-org/matrix-rust-sdk/commit/d8d9dae9d77bee48a2591b9aad9bd2fa466354cc) (Moderate, [GHSA-4qg4-cvh2-crgg](https://github.com/matrix-org/matrix-rust-sdk/security/advisories/GHSA-4qg4-cvh2-crgg)).

**Other changes**

- Add a new API `Device.encryptToDeviceEvent` to encrypt a to-device message using
Olm.
([#101](https://github.com/matrix-org/matrix-rust-sdk-crypto-wasm/pull/101))

# matrix-sdk-crypto-wasm v7.0.0

**BREAKING CHANGES**
Expand Down
33 changes: 33 additions & 0 deletions src/device.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Types for a `Device`.

use js_sys::{Array, Map, Promise};
use serde_json::Value;
use wasm_bindgen::prelude::*;

use crate::{
Expand Down Expand Up @@ -48,6 +49,38 @@ impl Device {
Ok(tuple)
}

/// 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
/// 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 JSON string containing the `content` of an
/// encrypted event, which be used to create the payload for a
/// `/sendToDevice` API.
#[wasm_bindgen(js_name = "encryptToDeviceEvent")]
pub async fn encrypt_to_device_event(
&self,
event_type: String,
content: JsValue,
) -> Result<String, JsError> {
let me = self.inner.clone();

// JSON-serialize the payload
let content: Value = serde_wasm_bindgen::from_value(content)?;

let raw_encrypted = me.encrypt_event_raw(event_type.as_str(), &content).await?;
Ok(raw_encrypted.into_json().get().to_owned())
}

/// 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 = JSON.parse(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