|
@@ -1,57 +1,73 @@
|
1
|
|
-use aes_gcm::{
|
2
|
|
- aead::{Aead, KeyInit},
|
3
|
|
- Aes256Gcm, Nonce as AesNonce,
|
|
1
|
+mod contract;
|
|
2
|
+mod crypto;
|
|
3
|
+pub mod error;
|
|
4
|
+mod exchange_client;
|
|
5
|
+
|
|
6
|
+pub use contract::{
|
|
7
|
+ add_participant, init_meeting, is_meet_participant, view_meet_participants,
|
|
8
|
+ view_moderator_account,
|
4
|
9
|
};
|
5
|
|
-use futures::{lock::Mutex, select, FutureExt};
|
6
|
|
-use itertools::Itertools;
|
7
|
|
-use rand::{RngCore, SeedableRng};
|
8
|
|
-use serde_json::json;
|
9
|
|
-use wasm_bindgen::prelude::*;
|
10
|
|
-
|
11
|
|
-use near_primitives_core::{account::id::AccountId, types::Nonce};
|
12
|
|
-use near_primitives_light::types::Finality;
|
13
|
|
-use near_rpc::client::{NearClient, Signer};
|
14
|
|
-
|
15
|
|
-use js_sys::Promise;
|
16
|
|
-
|
17
|
|
-use std::{ops::DerefMut, str::FromStr, sync::Arc};
|
18
|
10
|
|
19
|
|
-use blake2::{
|
20
|
|
- digest::{Update, VariableOutput},
|
21
|
|
- Blake2bVar,
|
22
|
|
-};
|
23
|
|
-
|
24
|
|
-pub mod errors;
|
25
|
|
-use common_api::crypto::prelude::*;
|
26
|
|
-
|
27
|
|
-use errors::{ApiError, ErrorType};
|
|
11
|
+use common_api::api::{Data, ExchangeMessage};
|
|
12
|
+use crypto::{decrypt, encrypt, secret};
|
|
13
|
+use error::ApiError;
|
|
14
|
+use exchange_client::{exchange, public_keys, receive};
|
|
15
|
+use futures::{select, FutureExt};
|
28
|
16
|
use gloo_timers::future::TimeoutFuture;
|
29
|
|
-
|
30
|
|
-#[allow(unused_macros)]
|
31
|
|
-macro_rules! console_log {
|
32
|
|
- ($($t:tt)*) => (web_sys::console::log_1(&format!($($t)*).into()))
|
33
|
|
-}
|
|
17
|
+use itertools::Itertools;
|
|
18
|
+use js_sys::Promise;
|
|
19
|
+use log::{info, warn};
|
|
20
|
+use near_primitives_core::{account::id::AccountId, hash::CryptoHash, types::Nonce};
|
|
21
|
+use near_rpc::client::Signer;
|
|
22
|
+use serde::{Deserialize, Serialize};
|
|
23
|
+use std::{collections::HashSet, str::FromStr, sync::Arc};
|
|
24
|
+use url::Url;
|
|
25
|
+use uuid::Uuid;
|
|
26
|
+use wasm_bindgen::prelude::*;
|
34
|
27
|
|
35
|
28
|
type Result<T> = std::result::Result<T, ApiError>;
|
36
|
29
|
|
37
|
30
|
#[wasm_bindgen(start)]
|
38
|
|
-pub fn start() -> std::result::Result<(), JsValue> {
|
|
31
|
+pub fn start() -> Result<()> {
|
39
|
32
|
console_error_panic_hook::set_once();
|
|
33
|
+ console_log::init().unwrap();
|
40
|
34
|
Ok(())
|
41
|
35
|
}
|
42
|
36
|
|
43
|
|
-struct Handler {
|
|
37
|
+fn to_value<T: Serialize>(value: &T) -> JsValue {
|
|
38
|
+ match serde_wasm_bindgen::to_value(value) {
|
|
39
|
+ Ok(value) => value,
|
|
40
|
+ Err(err) => err.into(),
|
|
41
|
+ }
|
|
42
|
+}
|
|
43
|
+
|
|
44
|
+pub struct Handler {
|
44
|
45
|
contract_id: AccountId,
|
45
|
|
- owner_sk: SecretKey,
|
46
|
|
- url: url::Url,
|
|
46
|
+ secret: [u8; 32],
|
|
47
|
+ exchange_url: url::Url,
|
|
48
|
+ rpc_url: url::Url,
|
|
49
|
+}
|
|
50
|
+
|
|
51
|
+impl Handler {
|
|
52
|
+ pub fn add_path(&self, path: &str) -> url::Url {
|
|
53
|
+ let mut url = self.exchange_url.clone();
|
|
54
|
+ url.set_path(path);
|
|
55
|
+ url
|
|
56
|
+ }
|
|
57
|
+}
|
|
58
|
+
|
|
59
|
+#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
60
|
+pub struct Meeting {
|
|
61
|
+ pub meet_id: Uuid,
|
|
62
|
+ pub transaction_id: CryptoHash,
|
47
|
63
|
}
|
48
|
64
|
|
49
|
65
|
#[wasm_bindgen]
|
50
|
66
|
#[derive(Debug, Clone)]
|
51
|
67
|
pub struct ProvisionerConfig {
|
52
|
68
|
contract_id: AccountId,
|
53
|
|
- rpc_url: url::Url,
|
54
|
|
- key_exchange_url: url::Url,
|
|
69
|
+ rpc_url: Url,
|
|
70
|
+ exchange_url: Url,
|
55
|
71
|
}
|
56
|
72
|
|
57
|
73
|
#[wasm_bindgen]
|
|
@@ -62,25 +78,23 @@ impl ProvisionerConfig {
|
62
|
78
|
rpc_url: &str,
|
63
|
79
|
exchange_url: &str,
|
64
|
80
|
) -> Result<ProvisionerConfig> {
|
65
|
|
- let rpc_url = url::Url::from_str(rpc_url)
|
66
|
|
- .map_err(|err| ApiError::new(ErrorType::NearClient, err.to_string()))?;
|
67
|
|
- let key_exchange_url = url::Url::from_str(exchange_url)
|
68
|
|
- .map_err(|err| ApiError::new(ErrorType::NearClient, err.to_string()))?;
|
69
|
|
- let contract_id = AccountId::from_str(&contract_id).map_err(Into::<ApiError>::into)?;
|
|
81
|
+ let rpc_url = Url::from_str(rpc_url)
|
|
82
|
+ .map_err(|err| ApiError::Other(format!("Bad rpc url, cause {err}")))?;
|
|
83
|
+ let exchange_url = Url::from_str(exchange_url)
|
|
84
|
+ .map_err(|err| ApiError::Other(format!("Bad exchange url, cause {err}")))?;
|
|
85
|
+ let contract_id = AccountId::from_str(&contract_id).map_err(ApiError::from)?;
|
70
|
86
|
|
71
|
87
|
Ok(Self {
|
72
|
88
|
contract_id,
|
73
|
89
|
rpc_url,
|
74
|
|
- key_exchange_url,
|
|
90
|
+ exchange_url,
|
75
|
91
|
})
|
76
|
92
|
}
|
77
|
93
|
}
|
78
|
94
|
|
79
|
95
|
#[wasm_bindgen]
|
80
|
96
|
pub struct KeyProvisioner {
|
81
|
|
- client: Arc<NearClient>,
|
82
|
|
- participants: Arc<Mutex<Option<Vec<String>>>>,
|
83
|
|
- signer: Arc<Mutex<Signer>>,
|
|
97
|
+ signer: Arc<Signer>,
|
84
|
98
|
handler: Arc<Handler>,
|
85
|
99
|
}
|
86
|
100
|
|
|
@@ -89,11 +103,7 @@ impl KeyProvisioner {
|
89
|
103
|
Arc::clone(&self.handler)
|
90
|
104
|
}
|
91
|
105
|
|
92
|
|
- fn client(&self) -> Arc<NearClient> {
|
93
|
|
- Arc::clone(&self.client)
|
94
|
|
- }
|
95
|
|
-
|
96
|
|
- fn signer(&self) -> Arc<Mutex<Signer>> {
|
|
106
|
+ fn signer(&self) -> Arc<Signer> {
|
97
|
107
|
Arc::clone(&self.signer)
|
98
|
108
|
}
|
99
|
109
|
}
|
|
@@ -105,29 +115,25 @@ impl KeyProvisioner {
|
105
|
115
|
keypair_str: String,
|
106
|
116
|
nonce: Nonce,
|
107
|
117
|
account_id: String,
|
108
|
|
- config: ProvisionerConfig,
|
|
118
|
+ ProvisionerConfig {
|
|
119
|
+ contract_id,
|
|
120
|
+ rpc_url,
|
|
121
|
+ exchange_url,
|
|
122
|
+ }: ProvisionerConfig,
|
109
|
123
|
) -> Result<KeyProvisioner> {
|
110
|
|
- let client = Arc::new(NearClient::new(config.rpc_url).map_err(ApiError::from)?);
|
111
|
|
- let signer = Arc::new(Mutex::new(
|
112
|
|
- Signer::from_secret_str(
|
113
|
|
- &keypair_str,
|
114
|
|
- AccountId::from_str(&account_id).map_err(Into::<ApiError>::into)?,
|
115
|
|
- nonce,
|
116
|
|
- )
|
117
|
|
- .map_err(ApiError::from)?,
|
118
|
|
- ));
|
|
124
|
+ let signer = Arc::new(Signer::from_secret_str(
|
|
125
|
+ &keypair_str,
|
|
126
|
+ AccountId::from_str(&account_id)?,
|
|
127
|
+ nonce,
|
|
128
|
+ )?);
|
119
|
129
|
let handler = Arc::new(Handler {
|
120
|
|
- contract_id: config.contract_id,
|
121
|
|
- owner_sk: new_secret()?,
|
122
|
|
- url: config.key_exchange_url,
|
|
130
|
+ contract_id,
|
|
131
|
+ secret: secret(),
|
|
132
|
+ exchange_url,
|
|
133
|
+ rpc_url,
|
123
|
134
|
});
|
124
|
135
|
|
125
|
|
- Ok(Self {
|
126
|
|
- client,
|
127
|
|
- signer,
|
128
|
|
- handler,
|
129
|
|
- participants: Arc::new(Mutex::new(None)),
|
130
|
|
- })
|
|
136
|
+ Ok(Self { signer, handler })
|
131
|
137
|
}
|
132
|
138
|
|
133
|
139
|
/// Initializes meeting by calling the contract and providing there a set of participants' keys
|
|
@@ -136,66 +142,37 @@ impl KeyProvisioner {
|
136
|
142
|
///
|
137
|
143
|
/// - participants_set - The [`js_sys::Set`] represents hash set of participants' keys
|
138
|
144
|
/// - timeout_ms - The [`u32`] that represents milliseconds that were given not to be exceeded
|
139
|
|
- pub fn init(&self, participants_set: js_sys::Set, timeout_ms: u32) -> Promise {
|
|
145
|
+ pub fn init_meeting(&self, participants_set: js_sys::Set, timeout_ms: u32) -> Promise {
|
140
|
146
|
let handler = self.handler();
|
141
|
|
- let client = self.client();
|
142
|
147
|
let signer = self.signer();
|
143
|
|
- let participants_lock = self.participants.clone();
|
144
|
148
|
|
145
|
|
- let init = async move {
|
146
|
|
- let exchange_uuid = uuid::Uuid::new_v4();
|
147
|
|
- let (contract_id, owner_pk) = (
|
148
|
|
- handler.contract_id.clone(),
|
149
|
|
- PublicKey::from(&handler.owner_sk),
|
150
|
|
- );
|
151
|
|
-
|
152
|
|
- let res: Vec<Result<String>> = participants_set
|
153
|
|
- .keys()
|
|
149
|
+ let init_meeting = async move {
|
|
150
|
+ let participants: HashSet<AccountId> = participants_set
|
|
151
|
+ .values()
|
154
|
152
|
.into_iter()
|
155
|
|
- .map(|item| {
|
156
|
|
- item.map(|it| {
|
157
|
|
- it.as_string()
|
158
|
|
- .ok_or_else(|| {
|
159
|
|
- ApiError::new(
|
160
|
|
- ErrorType::Other,
|
161
|
|
- "participants_set is empty".to_owned(),
|
162
|
|
- )
|
163
|
|
- })
|
164
|
|
- .map_err(ApiError::from)
|
165
|
|
- })
|
|
153
|
+ .map_ok(|it| {
|
|
154
|
+ let Some(acc_id) = it.as_string() else {
|
|
155
|
+ return Err(ApiError::Other("Set item type isn't a string".to_owned()));
|
|
156
|
+ };
|
|
157
|
+
|
|
158
|
+ AccountId::from_str(&acc_id).map_err(ApiError::from)
|
166
|
159
|
})
|
|
160
|
+ .flatten_ok()
|
167
|
161
|
.try_collect()?;
|
168
|
162
|
|
169
|
|
- let participants: Vec<String> = res.into_iter().try_collect()?;
|
170
|
|
-
|
171
|
|
- client
|
172
|
|
- .function_call(
|
173
|
|
- signer.lock().await.deref_mut(),
|
174
|
|
- &contract_id,
|
175
|
|
- "init_meeting",
|
176
|
|
- )
|
177
|
|
- .gas(near_units::parse_gas!("20 T") as u64)
|
178
|
|
- .args(json!({
|
179
|
|
- "owner_public_key": base64::encode(owner_pk.to_bytes()),
|
180
|
|
- "id": exchange_uuid.to_string(),
|
181
|
|
- "participants": participants,
|
182
|
|
- }))
|
183
|
|
- .build()
|
184
|
|
- .map_err(ApiError::from)?
|
185
|
|
- .commit(Finality::Final)
|
186
|
|
- .await
|
187
|
|
- .map_err(ApiError::from)?;
|
188
|
|
-
|
189
|
|
- *participants_lock.lock_owned().await = Some(participants);
|
190
|
|
-
|
191
|
|
- Ok(JsValue::from_str(&exchange_uuid.to_string()))
|
|
163
|
+ let (meet_id, transaction_id) = init_meeting(&handler, &signer, participants).await?;
|
|
164
|
+
|
|
165
|
+ Ok(to_value(&Meeting {
|
|
166
|
+ meet_id,
|
|
167
|
+ transaction_id,
|
|
168
|
+ }))
|
192
|
169
|
};
|
193
|
170
|
|
194
|
171
|
wasm_bindgen_futures::future_to_promise(async move {
|
195
|
172
|
select! {
|
196
|
|
- uuid = init.fuse() => uuid,
|
|
173
|
+ meet = init_meeting.fuse() => meet,
|
197
|
174
|
_ = TimeoutFuture::new(timeout_ms).fuse() => {
|
198
|
|
- Err(JsValue::from(ApiError::new(ErrorType::Other, "The initialization has been timed out".to_string())))
|
|
175
|
+ Err(ApiError::CallTimeout("The initialization has been timed out".to_owned()).into())
|
199
|
176
|
}
|
200
|
177
|
}
|
201
|
178
|
})
|
|
@@ -209,112 +186,67 @@ impl KeyProvisioner {
|
209
|
186
|
/// - timeout_ms - The [`u32`] that represents milliseconds that were given not to be exceeded
|
210
|
187
|
pub fn send_keys(&self, meeting_id: String, timeout_ms: u32) -> Promise {
|
211
|
188
|
let handler = self.handler();
|
212
|
|
- let client = self.client();
|
213
|
|
- let participants_lock = self.participants.clone();
|
|
189
|
+ let signer = self.signer();
|
|
190
|
+
|
214
|
191
|
let send_keys = async move {
|
215
|
|
- let guard = participants_lock.lock().await;
|
216
|
|
- let participants = guard
|
217
|
|
- .as_ref()
|
218
|
|
- .ok_or_else(|| ApiError::new(ErrorType::Other, "Empty participants".to_owned()))?;
|
219
|
|
-
|
220
|
|
- let (contract_id, url) = (handler.contract_id.clone(), &handler.url);
|
221
|
|
-
|
222
|
|
- let fetch_participants_keys = participants.iter().map(|participant| {
|
223
|
|
- let client_cp = client.clone();
|
224
|
|
- let contract_cp = contract_id.clone();
|
225
|
|
- let meeting_id_cp = meeting_id.clone();
|
226
|
|
- async move {
|
227
|
|
- loop {
|
228
|
|
- let resp = client_cp
|
229
|
|
- .view::<Option<String>>(
|
230
|
|
- &contract_cp,
|
231
|
|
- Finality::None,
|
232
|
|
- "public_key",
|
233
|
|
- Some(json!({
|
234
|
|
- "id": meeting_id_cp,
|
235
|
|
- "participant_id": participant.to_string()
|
236
|
|
- })),
|
237
|
|
- )
|
238
|
|
- .await
|
239
|
|
- .map_err(|err| ApiError::new(ErrorType::NearClient, err.to_string()))?
|
240
|
|
- .data();
|
241
|
|
-
|
242
|
|
- if let Some(key) = resp {
|
243
|
|
- return Ok::<(String, String), ApiError>((
|
244
|
|
- key,
|
245
|
|
- participant.to_string(),
|
246
|
|
- ));
|
|
192
|
+ let meet_id = Uuid::from_str(&meeting_id).map_err(ApiError::from)?;
|
|
193
|
+
|
|
194
|
+ let mut participants = view_meet_participants(&handler, meet_id)
|
|
195
|
+ .await?
|
|
196
|
+ .ok_or_else(|| {
|
|
197
|
+ ApiError::InvalidSessionUuid(format!("Wrong Session ID: {meet_id}"))
|
|
198
|
+ })?;
|
|
199
|
+
|
|
200
|
+ info!("Get a meeting participants {participants:?}");
|
|
201
|
+
|
|
202
|
+ while !participants.is_empty() {
|
|
203
|
+ let infos =
|
|
204
|
+ match public_keys(&handler, &signer, meet_id, participants.clone()).await {
|
|
205
|
+ Ok(infos) => infos,
|
|
206
|
+ Err(err) => {
|
|
207
|
+ warn!("Failed to fetch a public keys, cause {err:?}");
|
|
208
|
+ continue;
|
247
|
209
|
}
|
248
|
|
- }
|
249
|
|
- }
|
250
|
|
- });
|
|
210
|
+ };
|
251
|
211
|
|
252
|
|
- let participants_keys = futures::future::try_join_all(fetch_participants_keys).await?;
|
|
212
|
+ // remove infos that is already processed
|
|
213
|
+ for key in &infos {
|
|
214
|
+ participants.remove(&key.account_id);
|
|
215
|
+ }
|
253
|
216
|
|
254
|
|
- let keys: Vec<(PublicKey, String)> = participants_keys
|
255
|
|
- .into_iter()
|
256
|
|
- .map(|(pk, participant_id)| {
|
257
|
|
- base64::decode(pk)
|
258
|
|
- .map(|it| (it, participant_id))
|
259
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
260
|
|
- .and_then(|(pk_bytes, participant_id)| {
|
261
|
|
- PublicKey::try_from_bytes(&pk_bytes)
|
262
|
|
- .map(|it| (it, participant_id))
|
263
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
|
217
|
+ let messages = infos
|
|
218
|
+ .into_iter()
|
|
219
|
+ .map(|info| {
|
|
220
|
+ let sk = signer.secret_key();
|
|
221
|
+ let other_pk = info.public_key;
|
|
222
|
+ let msg = encrypt(sk, other_pk, meet_id, &handler.secret)?;
|
|
223
|
+ Ok::<ExchangeMessage, JsValue>(ExchangeMessage {
|
|
224
|
+ account_id: info.account_id,
|
|
225
|
+ message: Data {
|
|
226
|
+ data: msg,
|
|
227
|
+ moderator_pk: signer.public_key().to_owned(),
|
|
228
|
+ },
|
264
|
229
|
})
|
265
|
|
- })
|
266
|
|
- .try_collect()?;
|
267
|
|
-
|
268
|
|
- let aes_secret = base64::encode(new_secret()?.to_bytes());
|
|
230
|
+ })
|
|
231
|
+ .try_collect()?;
|
269
|
232
|
|
270
|
|
- let encrypted_keys: Vec<(Vec<u8>, String)> = keys
|
271
|
|
- .into_iter()
|
272
|
|
- .map(|(pk, participant_id)| {
|
273
|
|
- let res_key = handler.owner_sk.exchange(&pk);
|
274
|
|
- encrypt(&res_key, aes_secret.as_bytes(), participant_id)
|
275
|
|
- })
|
276
|
|
- .try_collect()?;
|
|
233
|
+ exchange(&handler, &signer, meet_id, messages).await?;
|
|
234
|
+ }
|
277
|
235
|
|
278
|
|
- let meeting_url = url
|
279
|
|
- .join("meeting")
|
280
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
281
|
|
-
|
282
|
|
- let _: Vec<reqwest::Response> = futures::future::try_join_all(
|
283
|
|
- encrypted_keys.into_iter().map(|(bytes, participant_id)| {
|
284
|
|
- let client = reqwest::ClientBuilder::new().build().unwrap();
|
285
|
|
- client
|
286
|
|
- .post(meeting_url.clone())
|
287
|
|
- .query(&[
|
288
|
|
- ("id", serde_json::to_value(meeting_id.clone()).unwrap()),
|
289
|
|
- ("participant", serde_json::to_value(participant_id).unwrap()),
|
290
|
|
- ])
|
291
|
|
- .json(&serde_json::Value::String(base64::encode(bytes)))
|
292
|
|
- .send()
|
293
|
|
- }),
|
294
|
|
- )
|
295
|
|
- .await
|
296
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?
|
297
|
|
- .into_iter()
|
298
|
|
- .map(|it| {
|
299
|
|
- it.error_for_status()
|
300
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
301
|
|
- })
|
302
|
|
- .try_collect()?;
|
303
|
|
-
|
304
|
|
- Ok(JsValue::from_str(&aes_secret))
|
|
236
|
+ Ok(JsValue::from_str(&base64::encode(handler.secret)))
|
305
|
237
|
};
|
306
|
238
|
|
307
|
239
|
wasm_bindgen_futures::future_to_promise(async move {
|
308
|
240
|
select! {
|
309
|
241
|
aes_secret = send_keys.fuse() => aes_secret,
|
310
|
242
|
_ = TimeoutFuture::new(timeout_ms).fuse() => {
|
311
|
|
- Err(JsValue::from(ApiError::new(ErrorType::Other, "The send keys operation has been timed out".to_string())))
|
|
243
|
+ Err(ApiError::CallTimeout("The send keys operation has been timed out".to_owned()).into())
|
312
|
244
|
}
|
313
|
245
|
}
|
314
|
246
|
})
|
315
|
247
|
}
|
316
|
248
|
|
317
|
|
- /// Get participant's key from a blockchain
|
|
249
|
+ /// Get participant's key from a server
|
318
|
250
|
///
|
319
|
251
|
/// Arguments
|
320
|
252
|
///
|
|
@@ -322,182 +254,22 @@ impl KeyProvisioner {
|
322
|
254
|
/// - timeout_ms - The [`u32`] that represents milliseconds that were given not to be exceeded
|
323
|
255
|
pub fn get_key(&self, meeting_id: String, timeout_ms: u32) -> Promise {
|
324
|
256
|
let handler = self.handler();
|
325
|
|
- let client = self.client();
|
326
|
257
|
let signer = self.signer();
|
327
|
258
|
|
328
|
259
|
let get_key = async move {
|
329
|
|
- let (contract_id, sk, url) =
|
330
|
|
- (handler.contract_id.clone(), &handler.owner_sk, &handler.url);
|
331
|
|
-
|
332
|
|
- let msg = get_message(url, signer, &meeting_id).await?;
|
333
|
|
- loop {
|
334
|
|
- let owner_pub_key = client
|
335
|
|
- .view::<Option<String>>(
|
336
|
|
- &contract_id,
|
337
|
|
- Finality::None,
|
338
|
|
- "owner_key",
|
339
|
|
- Some(serde_json::json!({
|
340
|
|
- "id": meeting_id.to_string()
|
341
|
|
- })),
|
342
|
|
- )
|
343
|
|
- .await
|
344
|
|
- .map_err(|err| ApiError::new(ErrorType::NearClient, err.to_string()))?
|
345
|
|
- .data();
|
346
|
|
-
|
347
|
|
- if let Some(owner_pk) = owner_pub_key {
|
348
|
|
- let bytes = base64::decode(owner_pk)
|
349
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
350
|
|
- let owner_pk = PublicKey::try_from_bytes(&bytes)
|
351
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
352
|
|
- let key = sk.exchange(&owner_pk);
|
353
|
|
-
|
354
|
|
- let msg_bytes = base64::decode(msg)
|
355
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
356
|
|
- let decrypted_msg = decrypt(&key, &msg_bytes)?;
|
357
|
|
-
|
358
|
|
- return Ok(JsValue::from_str(
|
359
|
|
- std::str::from_utf8(&decrypted_msg)
|
360
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?,
|
361
|
|
- ));
|
362
|
|
- }
|
363
|
|
- }
|
|
260
|
+ let meet_id = Uuid::from_str(&meeting_id).map_err(ApiError::from)?;
|
|
261
|
+ let data = receive(&handler, &signer, meet_id).await?;
|
|
262
|
+ let secret = decrypt(signer.secret_key(), data.moderator_pk, meet_id, data.data)?;
|
|
263
|
+ Ok(JsValue::from_str(&base64::encode(secret)))
|
364
|
264
|
};
|
365
|
265
|
|
366
|
266
|
wasm_bindgen_futures::future_to_promise(async move {
|
367
|
267
|
select! {
|
368
|
268
|
key = get_key.fuse() => key,
|
369
|
269
|
_ = TimeoutFuture::new(timeout_ms).fuse() => {
|
370
|
|
- Err(JsValue::from(ApiError::new(ErrorType::Other, "The getting key operation has been timed out".to_string())))
|
371
|
|
- }
|
372
|
|
- }
|
373
|
|
- })
|
374
|
|
- }
|
375
|
|
-
|
376
|
|
- /// Pushes end-user's key to the blockchain
|
377
|
|
- ///
|
378
|
|
- /// Arguments
|
379
|
|
- ///
|
380
|
|
- /// - meeting_id - The [`String`] that indicates ID of the meeting room
|
381
|
|
- /// - timeout_ms - The [`u32`] that represents milliseconds that were given not to be exceeded
|
382
|
|
- pub fn push_to_near(&self, meeting_id: String, timeout_ms: u32) -> Promise {
|
383
|
|
- let handler = self.handler();
|
384
|
|
- let client = self.client();
|
385
|
|
- let signer = self.signer();
|
386
|
|
-
|
387
|
|
- let push_key = async move {
|
388
|
|
- let (contract_id, pk) = (
|
389
|
|
- handler.contract_id.clone(),
|
390
|
|
- PublicKey::from(&handler.owner_sk),
|
391
|
|
- );
|
392
|
|
- client
|
393
|
|
- .function_call(signer.lock().await.deref_mut(), &contract_id, "set_key")
|
394
|
|
- .gas(near_units::parse_gas!("300 T") as u64)
|
395
|
|
- .args(json!({
|
396
|
|
- "id": meeting_id.to_string(),
|
397
|
|
- "pk": base64::encode(pk.to_bytes()),
|
398
|
|
- }))
|
399
|
|
- .build()
|
400
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?
|
401
|
|
- .commit(Finality::None)
|
402
|
|
- .await
|
403
|
|
- .map_err(|err| ApiError::new(ErrorType::NearClient, err.to_string()))?;
|
404
|
|
-
|
405
|
|
- Ok(JsValue::undefined())
|
406
|
|
- };
|
407
|
|
-
|
408
|
|
- wasm_bindgen_futures::future_to_promise(async move {
|
409
|
|
- select! {
|
410
|
|
- exchange_uuid = push_key.fuse() => exchange_uuid,
|
411
|
|
- _ = TimeoutFuture::new(timeout_ms).fuse() => {
|
412
|
|
- Err(JsValue::from(ApiError::new(ErrorType::Other, "The initialization has been timed out".to_string())))
|
|
270
|
+ Err(ApiError::CallTimeout("The getting key operation has been timed out".to_owned()).into())
|
413
|
271
|
}
|
414
|
272
|
}
|
415
|
273
|
})
|
416
|
274
|
}
|
417
|
275
|
}
|
418
|
|
-
|
419
|
|
-/// Retrieves encrypted message from the server. That message should be dectypted to grant an access to the meeting.
|
420
|
|
-///
|
421
|
|
-/// Arguments
|
422
|
|
-///
|
423
|
|
-/// - url - The ['reqwest::Url'] that represents a handler's url
|
424
|
|
-/// - signer - The [`Arc<Mutex<Signer>>`] is a signer that is used to sign transactions
|
425
|
|
-/// - meeting_id - The [`&str`] represents ID of the meeting
|
426
|
|
-async fn get_message(
|
427
|
|
- url: &reqwest::Url,
|
428
|
|
- signer: Arc<Mutex<Signer>>,
|
429
|
|
- meeting_id: &str,
|
430
|
|
-) -> Result<String> {
|
431
|
|
- let signer = signer.lock().await;
|
432
|
|
- let http_client = reqwest::ClientBuilder::new()
|
433
|
|
- .build()
|
434
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
435
|
|
- let meeting_url = url
|
436
|
|
- .join("meeting")
|
437
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
438
|
|
- let meeting_id_json = serde_json::to_value(meeting_id)
|
439
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
440
|
|
- let signer_json = serde_json::to_value(signer.account().clone())
|
441
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?;
|
442
|
|
- loop {
|
443
|
|
- let fetch_msg = http_client
|
444
|
|
- .get(meeting_url.clone())
|
445
|
|
- .query(&[("id", &meeting_id_json), ("participant", &signer_json)])
|
446
|
|
- .send()
|
447
|
|
- .await
|
448
|
|
- .and_then(|it| it.error_for_status())
|
449
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))?
|
450
|
|
- .text()
|
451
|
|
- .await
|
452
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()));
|
453
|
|
-
|
454
|
|
- if fetch_msg.is_ok() {
|
455
|
|
- return fetch_msg;
|
456
|
|
- }
|
457
|
|
- }
|
458
|
|
-}
|
459
|
|
-
|
460
|
|
-fn new_secret() -> Result<SecretKey> {
|
461
|
|
- use rand_chacha::ChaChaRng;
|
462
|
|
- let mut chacha = ChaChaRng::from_entropy();
|
463
|
|
- let mut bytes = [0_u8; 32];
|
464
|
|
- chacha.fill_bytes(&mut bytes);
|
465
|
|
- SecretKey::try_from_bytes(&bytes)
|
466
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
467
|
|
-}
|
468
|
|
-
|
469
|
|
-fn encrypt(
|
470
|
|
- exchange_key: &[u8],
|
471
|
|
- secret: &[u8],
|
472
|
|
- participant_id: String,
|
473
|
|
-) -> Result<(Vec<u8>, String)> {
|
474
|
|
- aes(exchange_key)
|
475
|
|
- .and_then(|it: Aes256Gcm| {
|
476
|
|
- it.encrypt(AesNonce::from_slice(b"unique nonce"), secret)
|
477
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
478
|
|
- })
|
479
|
|
- .map(|encrypted_msg| (encrypted_msg, participant_id))
|
480
|
|
-}
|
481
|
|
-
|
482
|
|
-fn decrypt(exchange_key: &[u8], secret: &[u8]) -> Result<Vec<u8>> {
|
483
|
|
- aes(exchange_key).and_then(|it: Aes256Gcm| {
|
484
|
|
- it.decrypt(AesNonce::from_slice(b"unique nonce"), secret)
|
485
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
486
|
|
- })
|
487
|
|
-}
|
488
|
|
-
|
489
|
|
-fn aes(exchange_key: &[u8]) -> Result<Aes256Gcm> {
|
490
|
|
- Blake2bVar::new(32)
|
491
|
|
- .map(|mut kdf| {
|
492
|
|
- kdf.update(exchange_key);
|
493
|
|
- kdf.finalize_boxed()
|
494
|
|
- })
|
495
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
496
|
|
- .and_then(|it| {
|
497
|
|
- Aes256Gcm::new_from_slice(&it)
|
498
|
|
- .map_err(|err| ApiError::new(ErrorType::Other, err.to_string()))
|
499
|
|
- })
|
500
|
|
-}
|
501
|
|
-
|
502
|
|
-#[cfg(test)]
|
503
|
|
-mod tests {}
|