Skip to content

armgit / ente

Public Imported from GitHub
0

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

Extract cast pairing crypto into Rust

Manav Rathi7b9936271f7e
diff --git a/.github/workflows/mobile-lint.yml b/.github/workflows/mobile-lint.yml
index 9ba9bb6aee..2a6e2a0101 100644
--- a/.github/workflows/mobile-lint.yml
+++ b/.github/workflows/mobile-lint.yml
@@ -10,6 +10,7 @@ on:
- "rust/bindings/frb/**"
- "rust/Cargo.lock"
- "rust/Cargo.toml"
+ - "rust/crates/cast/**"
- "rust/crates/contacts/**"
- "rust/crates/core/**"
- "rust/crates/image/**"
diff --git a/.github/workflows/warm-caches.yml b/.github/workflows/warm-caches.yml
index ee4d0be84d..9ea535c09f 100644
--- a/.github/workflows/warm-caches.yml
+++ b/.github/workflows/warm-caches.yml
@@ -114,6 +114,8 @@ jobs:
- run: npm run build:wasm
+ - run: npm run build:cast-wasm
+
- run: npm run build:space-wasm
photos-desktop-ensu-android:
diff --git a/.github/workflows/web-lint.yml b/.github/workflows/web-lint.yml
index c0b1ff389b..a54b446a5a 100644
--- a/.github/workflows/web-lint.yml
+++ b/.github/workflows/web-lint.yml
@@ -4,8 +4,10 @@ on:
pull_request:
paths:
- "web/**"
+ - "rust/bindings/wasm/cast/**"
- "rust/bindings/wasm/ente-wasm/**"
- "rust/bindings/wasm/space/**"
+ - "rust/crates/cast/**"
- "rust/crates/space/**"
- "rust/crates/contacts/**"
- "rust/crates/core/**"
@@ -51,6 +53,8 @@ jobs:
- run: npm run build:wasm
+ - run: npm run build:cast-wasm
+
- run: npm run build:space-wasm
- run: npm run lint
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index 70eec2d82d..c36ab82f31 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -46,6 +46,7 @@ import 'package:photos/services/memory_share_service.dart';
import 'package:photos/services/sync/local_sync_service.dart';
import 'package:photos/services/sync/remote_sync_service.dart';
import "package:photos/settings/local_settings.dart";
+import "package:photos/src/rust/api/cast_api.dart";
import "package:photos/utils/dialog_util.dart";
import "package:photos/utils/file_key.dart";
import 'package:shared_preferences/shared_preferences.dart';
@@ -825,16 +826,12 @@ class CollectionsService {
Collection collection,
String publicKey,
) {
- final String payload = jsonEncode({
- "collectionID": collection.id,
- "castToken": castToken,
- "collectionKey": CryptoUtil.bin2base64(getCollectionKey(collection.id)),
- });
- final encPayload = CryptoUtil.sealSync(
- CryptoUtil.base642bin(base64Encode(payload.codeUnits)),
- CryptoUtil.base642bin(publicKey),
+ return sealCastPayload(
+ publicKey: publicKey,
+ collectionId: collection.id,
+ castToken: castToken,
+ collectionKey: CryptoUtil.bin2base64(getCollectionKey(collection.id)),
);
- return CryptoUtil.bin2base64(encPayload);
}
Future<List<User>> share(
diff --git a/mobile/native/apple/apps/cast/Cast/Models/CastModels.swift b/mobile/native/apple/apps/cast/Cast/Models/CastModels.swift
index 517c1ea599..2da95e5f99 100644
--- a/mobile/native/apple/apps/cast/Cast/Models/CastModels.swift
+++ b/mobile/native/apple/apps/cast/Cast/Models/CastModels.swift
@@ -105,16 +105,9 @@ enum CastSessionState: Equatable {
case error(String)
}
-struct CastPayload: Codable, Equatable {
- let collectionID: Int
- let collectionKey: String
- let castToken: String
-}
-
struct CastDevice {
let deviceCode: String
- let publicKey: Data
- let privateKey: Data
+ let receiver: CastReceiver
}
// MARK: - Server Response Models
diff --git a/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift b/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift
index e86791fa36..502d48a6f0 100644
--- a/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift
+++ b/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift
@@ -64,8 +64,7 @@ class RealCastPairingService {
}
func registerDevice() async throws -> CastDevice {
- let keys = generateKeyPair()
- let publicKeyBase64 = keys.publicKey.base64EncodedString()
+ let receiver = CastReceiver()
print("POST \(baseURL)/cast/device-info")
@@ -74,7 +73,7 @@ class RealCastPairingService {
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- let requestBody = ["publicKey": publicKeyBase64]
+ let requestBody = ["publicKey": receiver.publicKey()]
request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
let (data, response) = try await URLSession.shared.data(for: request)
@@ -93,8 +92,7 @@ class RealCastPairingService {
return CastDevice(
deviceCode: deviceResponse.deviceCode,
- publicKey: keys.publicKey,
- privateKey: keys.privateKey
+ receiver: receiver
)
}
@@ -155,11 +153,7 @@ class RealCastPairingService {
}
- let payload = try await decryptPayload(
- encryptedData: encryptedData,
- publicKey: device.publicKey,
- privateKey: device.privateKey
- )
+ let payload = try device.receiver.openPayload(encryptedPayload: encryptedData)
hasDeliveredPayload = true
stopPolling()
@@ -176,36 +170,6 @@ class RealCastPairingService {
}
}
- private func decryptPayload(encryptedData: String, publicKey: Data, privateKey: Data) async throws -> CastPayload {
- do {
- guard let encryptedBytes = Data(base64Encoded: encryptedData) else {
- throw CastError.decryptionError("Invalid encrypted cast payload")
- }
-
- let decryptedData = try openSealedBox(
- ciphertext: encryptedBytes,
- publicKey: publicKey,
- privateKey: privateKey
- )
-
- // Handle potential base64 preprocessing from mobile client
- let finalData: Data
- if let base64String = String(data: decryptedData, encoding: .utf8),
- let jsonData = Data(base64Encoded: base64String) {
- finalData = jsonData
- } else {
- finalData = decryptedData
- }
-
- let payload = try JSONDecoder().decode(CastPayload.self, from: finalData)
- return payload
- } catch {
- throw CastError.decryptionError(
- "Cast payload decryption failed: \(error.localizedDescription)"
- )
- }
- }
-
func stopPolling() {
guard isPolling else { return }
pollingTimer?.invalidate()
diff --git a/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
index cafd67f92f..324bb46725 100644
--- a/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
+++ b/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
@@ -343,7 +343,7 @@ class RealSlideshowService: ObservableObject {
}
private func fetchFilesBatch(castPayload: CastPayload, sinceTime: Int64) async throws -> (files: [[String: Any]], hasMore: Bool, latestUpdateTime: Int64) {
- let url = URL(string: "\(baseURL)/cast/diff?collectionID=\(castPayload.collectionID)&sinceTime=\(sinceTime)")!
+ let url = URL(string: "\(baseURL)/cast/diff?collectionID=\(castPayload.collectionId)&sinceTime=\(sinceTime)")!
var request = URLRequest(url: url)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 6e09e3ae47..14d77d5e4b 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2355,16 +2355,36 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "ente-cast"
+version = "0.0.0"
+dependencies = [
+ "ente-core",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "ente-cast-uniffi"
version = "0.0.0"
dependencies = [
+ "ente-cast",
"ente-core",
"ente-uniffi-log",
"thiserror 2.0.18",
"uniffi",
]
+[[package]]
+name = "ente-cast-wasm"
+version = "0.0.0"
+dependencies = [
+ "ente-cast",
+ "ente-wasm-log",
+ "wasm-bindgen",
+]
+
[[package]]
name = "ente-contacts"
version = "0.0.0"
@@ -2656,6 +2676,7 @@ dependencies = [
name = "ente_photos_rust"
version = "0.0.0"
dependencies = [
+ "ente-cast",
"ente-frb-log",
"ente-image",
"ente-photos",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 02ec3fc6c3..06e3417144 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -11,12 +11,14 @@ members = [
"bindings/uniffi/cast",
"bindings/uniffi/ensu",
"bindings/uniffi/log",
+ "bindings/wasm/cast",
"bindings/wasm/ente-wasm",
"bindings/wasm/core",
"bindings/wasm/log",
"bindings/wasm/space",
"crates/accounts",
"crates/assets",
+ "crates/cast",
"crates/contacts",
"crates/core",
"crates/ensu",
@@ -30,6 +32,7 @@ members = [
[workspace.dependencies]
ente-accounts = { path = "crates/accounts" }
ente-assets = { path = "crates/assets" }
+ente-cast = { path = "crates/cast" }
ente-contacts = { path = "crates/contacts" }
ente-core = { path = "crates/core" }
ente-ensu = { path = "crates/ensu" }
diff --git a/rust/bindings/frb/photos/Cargo.toml b/rust/bindings/frb/photos/Cargo.toml
index c077a5d970..bcb61d5fae 100644
--- a/rust/bindings/frb/photos/Cargo.toml
+++ b/rust/bindings/frb/photos/Cargo.toml
@@ -6,6 +6,7 @@ edition = "2024"
crate-type = ["cdylib", "staticlib"]
[dependencies]
+ente-cast.workspace = true
ente-frb-log.workspace = true
ente-image.workspace = true
ente-photos = { workspace = true, features = ["usearch"] }
diff --git a/rust/bindings/frb/photos/src/api/cast_api.rs b/rust/bindings/frb/photos/src/api/cast_api.rs
new file mode 100644
index 0000000000..028818f745
--- /dev/null
+++ b/rust/bindings/frb/photos/src/api/cast_api.rs
@@ -0,0 +1,17 @@
+#[flutter_rust_bridge::frb(sync)]
+pub fn seal_cast_payload(
+ public_key: String,
+ collection_id: i64,
+ cast_token: String,
+ collection_key: String,
+) -> Result<String, String> {
+ ente_cast::seal_payload(
+ &public_key,
+ &ente_cast::CastPayload {
+ collection_id,
+ cast_token,
+ collection_key,
+ },
+ )
+ .map_err(|error| error.to_string())
+}
diff --git a/rust/bindings/frb/photos/src/api/mod.rs b/rust/bindings/frb/photos/src/api/mod.rs
index 0a41546cb8..7fed6c2f16 100644
--- a/rust/bindings/frb/photos/src/api/mod.rs
+++ b/rust/bindings/frb/photos/src/api/mod.rs
@@ -1,3 +1,4 @@
+pub mod cast_api;
pub mod image_processing_api;
pub mod init;
#[cfg(any(feature = "flutter", frb_expand))]
diff --git a/rust/bindings/uniffi/cast/Cargo.toml b/rust/bindings/uniffi/cast/Cargo.toml
index 3b7ccda7eb..02e018e044 100644
--- a/rust/bindings/uniffi/cast/Cargo.toml
+++ b/rust/bindings/uniffi/cast/Cargo.toml
@@ -7,6 +7,7 @@ name = "cast"
crate-type = ["staticlib", "cdylib"]
[dependencies]
+ente-cast.workspace = true
ente-core.workspace = true
ente-uniffi-log.workspace = true
thiserror.workspace = true
diff --git a/rust/bindings/uniffi/cast/src/lib.rs b/rust/bindings/uniffi/cast/src/lib.rs
index f50992bc92..2a104485ee 100644
--- a/rust/bindings/uniffi/cast/src/lib.rs
+++ b/rust/bindings/uniffi/cast/src/lib.rs
@@ -2,6 +2,8 @@ uniffi::setup_scaffolding!("cast");
pub mod log;
+use std::sync::Arc;
+
use ente_core::crypto;
use thiserror::Error;
@@ -17,35 +19,50 @@ impl From<crypto::Error> for CastCryptoError {
}
}
-#[derive(Debug, Clone, uniffi::Record)]
-pub struct CastKeyPair {
- pub public_key: Vec<u8>,
- pub private_key: Vec<u8>,
+impl From<ente_cast::Error> for CastCryptoError {
+ fn from(err: ente_cast::Error) -> Self {
+ CastCryptoError::Message(ente_core::error::chain(&err))
+ }
}
-#[uniffi::export]
-pub fn generate_key_pair() -> CastKeyPair {
- let private_key = crypto::SecretKey::generate();
- let public_key = private_key.public_key();
- CastKeyPair {
- public_key: public_key.as_bytes().to_vec(),
- private_key: private_key.as_bytes().to_vec(),
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct CastPayload {
+ pub collection_id: i64,
+ pub cast_token: String,
+ pub collection_key: String,
+}
+
+impl From<ente_cast::CastPayload> for CastPayload {
+ fn from(payload: ente_cast::CastPayload) -> Self {
+ Self {
+ collection_id: payload.collection_id,
+ cast_token: payload.cast_token,
+ collection_key: payload.collection_key,
+ }
}
}
+#[derive(uniffi::Object)]
+pub struct CastReceiver {
+ inner: ente_cast::ReceiverCredentials,
+}
+
#[uniffi::export]
-pub fn open_sealed_box(
- ciphertext: Vec<u8>,
- public_key: Vec<u8>,
- private_key: Vec<u8>,
-) -> Result<Vec<u8>, CastCryptoError> {
- let public_key = crypto::PublicKey::try_from_slice(&public_key)?;
- let private_key = crypto::SecretKey::try_from_slice(&private_key)?;
- Ok(crypto::sealed::open(
- &ciphertext,
- &public_key,
- &private_key,
- )?)
+impl CastReceiver {
+ #[uniffi::constructor]
+ pub fn new() -> Arc<Self> {
+ Arc::new(Self {
+ inner: ente_cast::ReceiverCredentials::generate(),
+ })
+ }
+
+ pub fn public_key(&self) -> String {
+ self.inner.public_key()
+ }
+
+ pub fn open_payload(&self, encrypted_payload: String) -> Result<CastPayload, CastCryptoError> {
+ Ok(self.inner.open_payload(&encrypted_payload)?.into())
+ }
}
#[uniffi::export]
diff --git a/rust/bindings/wasm/cast/Cargo.toml b/rust/bindings/wasm/cast/Cargo.toml
new file mode 100644
index 0000000000..5ea2c9ba61
--- /dev/null
+++ b/rust/bindings/wasm/cast/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "ente-cast-wasm"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-cast.workspace = true
+ente-wasm-log.workspace = true
+wasm-bindgen.workspace = true
diff --git a/rust/bindings/wasm/cast/src/lib.rs b/rust/bindings/wasm/cast/src/lib.rs
new file mode 100644
index 0000000000..10eb1ecab7
--- /dev/null
+++ b/rust/bindings/wasm/cast/src/lib.rs
@@ -0,0 +1,81 @@
+use ente_cast::ReceiverCredentials;
+use wasm_bindgen::prelude::*;
+
+use ente_wasm_log as _;
+
+#[wasm_bindgen]
+pub struct CastReceiver {
+ inner: ReceiverCredentials,
+}
+
+impl Default for CastReceiver {
+ fn default() -> Self {
+ Self {
+ inner: ReceiverCredentials::generate(),
+ }
+ }
+}
+
+#[wasm_bindgen]
+impl CastReceiver {
+ #[wasm_bindgen(constructor)]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ #[wasm_bindgen(getter, js_name = publicKey)]
+ pub fn public_key(&self) -> String {
+ self.inner.public_key()
+ }
+
+ #[wasm_bindgen(js_name = openPayload)]
+ pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload, JsError> {
+ Ok(self.inner.open_payload(encrypted_payload)?.into())
+ }
+}
+
+#[wasm_bindgen]
+pub struct CastPayload {
+ inner: ente_cast::CastPayload,
+}
+
+impl From<ente_cast::CastPayload> for CastPayload {
+ fn from(inner: ente_cast::CastPayload) -> Self {
+ Self { inner }
+ }
+}
+
+#[wasm_bindgen]
+impl CastPayload {
+ #[wasm_bindgen(getter, js_name = collectionID)]
+ pub fn collection_id(&self) -> i64 {
+ self.inner.collection_id
+ }
+
+ #[wasm_bindgen(getter, js_name = castToken)]
+ pub fn cast_token(&self) -> String {
+ self.inner.cast_token.clone()
+ }
+
+ #[wasm_bindgen(getter, js_name = collectionKey)]
+ pub fn collection_key(&self) -> String {
+ self.inner.collection_key.clone()
+ }
+}
+
+#[wasm_bindgen(js_name = sealPayload)]
+pub fn seal_payload(
+ public_key: &str,
+ collection_id: i64,
+ cast_token: String,
+ collection_key: String,
+) -> Result<String, JsError> {
+ Ok(ente_cast::seal_payload(
+ public_key,
+ &ente_cast::CastPayload {
+ collection_id,
+ cast_token,
+ collection_key,
+ },
+ )?)
+}
diff --git a/rust/crates/cast/Cargo.toml b/rust/crates/cast/Cargo.toml
new file mode 100644
index 0000000000..1edcfc6e31
--- /dev/null
+++ b/rust/crates/cast/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "ente-cast"
+edition = "2024"
+
+[dependencies]
+ente-core.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
diff --git a/rust/crates/cast/src/lib.rs b/rust/crates/cast/src/lib.rs
new file mode 100644
index 0000000000..7b883dbb80
--- /dev/null
+++ b/rust/crates/cast/src/lib.rs
@@ -0,0 +1,108 @@
+use ente_core::b64;
+use ente_core::crypto::{self, PublicKey, SecretKey};
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum Error {
+ #[error("Invalid base64: {0}")]
+ Base64(#[from] b64::DecodeError),
+
+ #[error(transparent)]
+ Crypto(#[from] crypto::Error),
+
+ #[error("Invalid cast payload: {0}")]
+ Payload(#[from] serde_json::Error),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CastPayload {
+ #[serde(rename = "collectionID")]
+ pub collection_id: i64,
+ pub cast_token: String,
+ pub collection_key: String,
+}
+
+pub struct ReceiverCredentials {
+ secret_key: SecretKey,
+}
+
+impl ReceiverCredentials {
+ pub fn generate() -> Self {
+ Self {
+ secret_key: SecretKey::generate(),
+ }
+ }
+
+ pub fn public_key(&self) -> String {
+ b64::encode(self.secret_key.public_key().as_bytes())
+ }
+
+ pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload> {
+ let ciphertext = b64::decode(encrypted_payload)?;
+ let public_key = self.secret_key.public_key();
+ let plaintext = crypto::sealed::open(&ciphertext, &public_key, &self.secret_key)?;
+ Ok(serde_json::from_slice(&plaintext)?)
+ }
+}
+
+pub fn seal_payload(public_key: &str, payload: &CastPayload) -> Result<String> {
+ let public_key = PublicKey::try_from_slice(&b64::decode(public_key)?)?;
+ let plaintext = serde_json::to_vec(payload)?;
+ Ok(b64::encode(&crypto::sealed::seal(&plaintext, &public_key)?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn payload() -> CastPayload {
+ CastPayload {
+ collection_id: 42,
+ cast_token: "cast_token".into(),
+ collection_key: "collection_key".into(),
+ }
+ }
+
+ #[test]
+ fn round_trip() {
+ let receiver = ReceiverCredentials::generate();
+ let encrypted = seal_payload(&receiver.public_key(), &payload()).unwrap();
+ assert_eq!(receiver.open_payload(&encrypted).unwrap(), payload());
+ }
+
+ #[test]
+ fn payload_uses_existing_wire_names() {
+ assert_eq!(
+ serde_json::to_string(&payload()).unwrap(),
+ r#"{"collectionID":42,"castToken":"cast_token","collectionKey":"collection_key"}"#
+ );
+ }
+
+ #[test]
+ fn opens_existing_libsodium_payload() {
+ let secret_key: [u8; 32] = std::array::from_fn(|index| index as u8);
+ let receiver = ReceiverCredentials {
+ secret_key: SecretKey::from_seed(&secret_key).unwrap(),
+ };
+ assert_eq!(
+ receiver.public_key(),
+ "j0DFrbaPJWJK5bIU6nZ6bslNgp09e14a0bpvPiE4KF8="
+ );
+
+ let encrypted = "kWxjziNMQxuQ/vqdErOGA3Rw14SfGgCy/wRRbsIIRncPWMHB52ezfFT+403RPw5oKuQonUgwWlQNBVcNOnKn54v8nkJuTxMyrqH2YLghbnhVFV/L+JICvFwZvcBBCN7tNNtjtOENJXn/hHaLbT+LwUAtrwwOPWiuca0vRdg=";
+ assert_eq!(receiver.open_payload(encrypted).unwrap(), payload());
+ }
+
+ #[test]
+ fn rejects_invalid_inputs() {
+ assert!(seal_payload("not base64", &payload()).is_err());
+
+ let receiver = ReceiverCredentials::generate();
+ assert!(receiver.open_payload("not base64").is_err());
+ assert!(receiver.open_payload(&b64::encode(&[0; 48])).is_err());
+ }
+}
diff --git a/web/.gitignore b/web/.gitignore
index 717f609f5e..f80cbdb8b5 100644
--- a/web/.gitignore
+++ b/web/.gitignore
@@ -11,5 +11,6 @@ out/
next-env.d.ts
packages/wasm/pkg/
+packages/wasm/cast/pkg/
packages/wasm/space/pkg/
packages/wasm-core/pkg/
diff --git a/web/apps/cast/package.json b/web/apps/cast/package.json
index 9e11552bf0..8db93f800a 100644
--- a/web/apps/cast/package.json
+++ b/web/apps/cast/package.json
@@ -7,6 +7,7 @@
],
"dependencies": {
"ente-base": "*",
+ "ente-cast-wasm": "*",
"ente-media": "*"
},
"devDependencies": {
diff --git a/web/apps/cast/src/pages/index.tsx b/web/apps/cast/src/pages/index.tsx
index 0add3ba4f2..bb4b6be257 100644
--- a/web/apps/cast/src/pages/index.tsx
+++ b/web/apps/cast/src/pages/index.tsx
@@ -4,7 +4,7 @@ import {
readCastData,
storeCastData,
} from "@/services/cast-data";
-import { getCastPayload, register } from "@/services/pair";
+import { getCastPayload, register, type Registration } from "@/services/pair";
import { Box, Stack, styled, Typography } from "@mui/material";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
@@ -14,19 +14,14 @@ import React, { useEffect, useState } from "react";
import { advertiseOnChromecast } from "../services/chromecast-receiver";
const Page: React.FC = () => {
- const [publicKey, setPublicKey] = useState<string | undefined>();
- const [privateKey, setPrivateKey] = useState<string | undefined>();
- const [pairingCode, setPairingCode] = useState<string | undefined>();
+ const [registration, setRegistration] = useState<Registration>();
+ const pairingCode = registration?.pairingCode;
const router = useRouter();
useEffect(() => {
if (!pairingCode) {
- void register().then((r) => {
- setPublicKey(r.publicKey);
- setPrivateKey(r.privateKey);
- setPairingCode(r.pairingCode);
- });
+ void register().then(setRegistration);
} else {
clearCastData();
advertiseOnChromecast(
@@ -37,28 +32,24 @@ const Page: React.FC = () => {
}, [pairingCode]);
useEffect(() => {
- if (!publicKey || !privateKey || !pairingCode) return;
+ if (!registration) return;
const pollTick = async () => {
try {
- const data = await getCastPayload({
- publicKey,
- privateKey,
- pairingCode,
- });
+ const data = await getCastPayload(registration);
if (!data) return;
storeCastData(data);
await router.push("/slideshow");
} catch (e) {
log.warn("Failed to get cast data", e);
- setPairingCode(undefined);
+ setRegistration(undefined);
}
};
const interval = setInterval(pollTick, 2000);
return () => clearInterval(interval);
- }, [publicKey, privateKey, pairingCode, router]);
+ }, [registration, router]);
return (
<Container>
diff --git a/web/apps/cast/src/services/pair.ts b/web/apps/cast/src/services/pair.ts
index ee7026e8cb..ac1ca22967 100644
--- a/web/apps/cast/src/services/pair.ts
+++ b/web/apps/cast/src/services/pair.ts
@@ -1,24 +1,24 @@
-import { boxSealOpenBytes, generateKeyPair } from "ente-base/crypto";
import { ensureOk, publicRequestHeaders } from "ente-base/http";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
+import type { CastReceiver } from "ente-cast-wasm";
import { wait } from "ente-utils/promise";
import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
export interface Registration {
pairingCode: string;
- publicKey: string;
- privateKey: string;
+ receiver: CastReceiver;
}
export const register = async (): Promise<Registration> => {
- const { publicKey, privateKey } = await generateKeyPair();
+ const { CastReceiver } = await import("ente-cast-wasm");
+ const receiver = new CastReceiver();
let pairingCode: string | undefined;
while (true) {
try {
- pairingCode = await registerDevice(publicKey);
+ pairingCode = await registerDevice(receiver.publicKey);
} catch (e) {
log.error("Failed to register public key with server", e);
}
@@ -26,7 +26,7 @@ export const register = async (): Promise<Registration> => {
await wait(10000);
}
- return { pairingCode, publicKey, privateKey };
+ return { pairingCode, receiver };
};
const registerDevice = async (publicKey: string) => {
@@ -40,26 +40,26 @@ const registerDevice = async (publicKey: string) => {
.deviceCode;
};
-const CastPayload = z.object({
- castToken: z.string(),
- collectionID: z.number(),
- collectionKey: z.string(),
-});
-
-export type CastPayload = z.infer<typeof CastPayload>;
+export interface CastPayload {
+ castToken: string;
+ collectionID: number;
+ collectionKey: string;
+}
export const getCastPayload = async (
registration: Registration,
): Promise<CastPayload | undefined> => {
- const { pairingCode, publicKey, privateKey } = registration;
+ const { pairingCode, receiver } = registration;
const encryptedCastData = await getEncryptedCastData(pairingCode);
if (!encryptedCastData) return undefined;
- const jsonString = new TextDecoder().decode(
- await boxSealOpenBytes(encryptedCastData, { publicKey, privateKey }),
- );
- return CastPayload.parse(JSON.parse(jsonString));
+ const payload = receiver.openPayload(encryptedCastData);
+ return {
+ castToken: payload.castToken,
+ collectionID: Number(payload.collectionID),
+ collectionKey: payload.collectionKey,
+ };
};
const getEncryptedCastData = async (code: string) => {
diff --git a/web/apps/photos/package.json b/web/apps/photos/package.json
index e59fc12993..d1f2fa3acf 100644
--- a/web/apps/photos/package.json
+++ b/web/apps/photos/package.json
@@ -15,6 +15,7 @@
"debounce": "2.2.0",
"ente-accounts": "*",
"ente-base": "*",
+ "ente-cast-wasm": "*",
"ente-contacts-web": "*",
"ente-gallery": "*",
"ente-media": "*",
diff --git a/web/apps/photos/src/services/cast.ts b/web/apps/photos/src/services/cast.ts
index b327f32393..fdb6085dce 100644
--- a/web/apps/photos/src/services/cast.ts
+++ b/web/apps/photos/src/services/cast.ts
@@ -1,4 +1,3 @@
-import { boxSeal } from "ente-base/crypto";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { newID } from "ente-base/id";
import { apiURL } from "ente-base/origins";
@@ -35,12 +34,13 @@ export const publishCastPayload = async (
const castToken = newID("cast_");
- const payload = JSON.stringify({
+ const { sealPayload } = await import("ente-cast-wasm");
+ const encryptedPayload = sealPayload(
+ publicKey,
+ BigInt(collection.id),
castToken,
- collectionID: collection.id,
- collectionKey: collection.key,
- });
- const encryptedPayload = await boxSeal(btoa(payload), publicKey);
+ collection.key,
+ );
const res = await fetch(await apiURL("/cast/cast-data"), {
method: "POST",
headers: await authenticatedRequestHeaders(),
diff --git a/web/package-lock.json b/web/package-lock.json
index 442fe57b07..9d9cef28d4 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -10,6 +10,7 @@
"workspaces": [
"apps/*",
"packages/*",
+ "packages/wasm/cast",
"packages/wasm/space"
],
"devDependencies": {
@@ -134,6 +135,7 @@
"version": "0.0.0",
"dependencies": {
"ente-base": "*",
+ "ente-cast-wasm": "*",
"ente-media": "*"
},
"devDependencies": {
@@ -289,6 +291,7 @@
"debounce": "2.2.0",
"ente-accounts": "*",
"ente-base": "*",
+ "ente-cast-wasm": "*",
"ente-contacts-web": "*",
"ente-gallery": "*",
"ente-media": "*",
@@ -4752,6 +4755,10 @@
"resolved": "packages/build-config",
"link": true
},
+ "node_modules/ente-cast-wasm": {
+ "resolved": "packages/wasm/cast",
+ "link": true
+ },
"node_modules/ente-contacts-web": {
"resolved": "packages/contacts",
"link": true
@@ -11393,6 +11400,14 @@
"wasm-pack": "0.15.0"
}
},
+ "packages/wasm/cast": {
+ "name": "ente-cast-wasm",
+ "version": "0.0.0",
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+ },
"packages/wasm/space": {
"name": "ente-space-wasm",
"version": "0.0.0",
diff --git a/web/package.json b/web/package.json
index abb93862a4..53a8d89db7 100644
--- a/web/package.json
+++ b/web/package.json
@@ -5,6 +5,7 @@
"workspaces": [
"apps/*",
"packages/*",
+ "packages/wasm/cast",
"packages/wasm/space"
],
"scripts": {
@@ -12,7 +13,8 @@
"build:accounts": "npm run build:wasm && npm exec --workspace accounts -- next build --webpack",
"build:albums": "npm run build:wasm && npm exec --workspace albums -- next build --webpack",
"build:auth": "npm run build:wasm && npm exec --workspace auth -- next build --webpack",
- "build:cast": "npm run build:wasm && npm exec --workspace cast -- next build --webpack",
+ "build:cast": "npm run build:wasm && npm run build:cast-wasm && npm exec --workspace cast -- next build --webpack",
+ "build:cast-wasm": "npm run build --workspace ente-cast-wasm -- --no-pack",
"build:embed": "npm run build:wasm && npm exec --workspace embed -- next build --webpack",
"build:ensu": "npm run build:wasm && npm exec --workspace ensu -- next build --webpack",
"build:legacy": "npm run build:wasm && npm exec --workspace legacy -- next build --webpack",
@@ -20,7 +22,7 @@
"build:memories": "npm run build:wasm && npm exec --workspace memories -- next build --webpack && npm run build:post --workspace memories",
"build:paste": "npm run build:wasm && npm exec --workspace paste -- next build --webpack && npm run build:post --workspace paste",
"build:payments": "npm run build --workspace payments",
- "build:photos": "npm run build:wasm && npm exec --workspace photos -- next build --webpack",
+ "build:photos": "npm run build:wasm && npm run build:cast-wasm && npm exec --workspace photos -- next build --webpack",
"build:share": "npm run build:wasm && npm exec --workspace share -- next build --webpack && npm run build:post --workspace share",
"build:space": "npm run build:wasm && npm run build:space-wasm && npm exec --workspace space -- next build --webpack && npm run build:post --workspace space",
"build:space-wasm": "npm run build --workspace ente-space-wasm -- --no-pack",
@@ -30,7 +32,7 @@
"dev:accounts": "npm run build:wasm && npm exec --workspace accounts -- next dev --webpack -p 3001",
"dev:albums": "npm run build:wasm && npm exec --workspace albums -- next dev --webpack -p 3002",
"dev:auth": "npm run build:wasm && npm exec --workspace auth -- next dev --webpack -p 3003",
- "dev:cast": "npm run build:wasm && npm exec --workspace cast -- next dev --webpack -p 3004",
+ "dev:cast": "npm run build:wasm && npm run build:cast-wasm && npm exec --workspace cast -- next dev --webpack -p 3004",
"dev:embed": "npm run build:wasm && npm exec --workspace embed -- next dev --webpack -p 3006",
"dev:ensu": "npm run build:wasm && npm exec --workspace ensu -- next dev --webpack -p 3007",
"dev:legacy": "npm run build:wasm && npm exec --workspace legacy -- next dev --webpack -p 3011",
@@ -38,7 +40,7 @@
"dev:memories": "npm run build:wasm && npm exec --workspace memories -- next dev --webpack -p 3010",
"dev:paste": "npm run build:wasm && npm exec --workspace paste -- next dev --webpack -p 3008",
"dev:payments": "npm run dev --workspace payments",
- "dev:photos": "npm run build:wasm && npm exec --workspace photos -- next dev --webpack -p 3000",
+ "dev:photos": "npm run build:wasm && npm run build:cast-wasm && npm exec --workspace photos -- next dev --webpack -p 3000",
"dev:share": "npm run build:wasm && npm exec --workspace share -- next dev --webpack -p 3005",
"dev:space": "npm run build:wasm && npm run build:space-wasm && npm exec --workspace space -- next dev --webpack -p 3013",
"dev:twoof3": "npm exec --workspace twoof3 -- next dev --webpack -p 3012",
diff --git a/web/packages/wasm/cast/eslint.config.mjs b/web/packages/wasm/cast/eslint.config.mjs
new file mode 100644
index 0000000000..e6c7d4d3b0
--- /dev/null
+++ b/web/packages/wasm/cast/eslint.config.mjs
@@ -0,0 +1,3 @@
+import config from "ente-build-config/eslintrc-base.mjs";
+
+export default [...config, { ignores: ["pkg/"] }];
diff --git a/web/packages/wasm/cast/index.ts b/web/packages/wasm/cast/index.ts
new file mode 100644
index 0000000000..2aa868ce0e
--- /dev/null
+++ b/web/packages/wasm/cast/index.ts
@@ -0,0 +1 @@
+export * from "./pkg/ente_cast_wasm";
diff --git a/web/packages/wasm/cast/package.json b/web/packages/wasm/cast/package.json
new file mode 100644
index 0000000000..2b1453d992
--- /dev/null
+++ b/web/packages/wasm/cast/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "ente-cast-wasm",
+ "version": "0.0.0",
+ "private": true,
+ "exports": {
+ ".": {
+ "types": "./index.ts",
+ "import": "./index.ts"
+ }
+ },
+ "module": "./index.ts",
+ "types": "./index.ts",
+ "scripts": {
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/cast --target bundler --out-dir ../../../../web/packages/wasm/cast/pkg"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+}
diff --git a/web/packages/wasm/cast/tsconfig.json b/web/packages/wasm/cast/tsconfig.json
new file mode 100644
index 0000000000..3f3b6cd165
--- /dev/null
+++ b/web/packages/wasm/cast/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "ente-build-config/tsconfig-typecheck.json", "include": ["."] }