Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f2905df169 | |||
|
|
c386e8d5cb |
||
|
|
74fb46990e |
14 changed files with 950 additions and 507 deletions
|
|
@ -20,6 +20,7 @@ pub fn run() {
|
||||||
accessibility_backend::accessibility_get_initial_scale,
|
accessibility_backend::accessibility_get_initial_scale,
|
||||||
accessibility_backend::accessibility_set_initial_scale,
|
accessibility_backend::accessibility_set_initial_scale,
|
||||||
mtp_backend::mtp_request,
|
mtp_backend::mtp_request,
|
||||||
|
mtp_backend::mtp_send_sealed_relay,
|
||||||
mtp_backend::mtp_status,
|
mtp_backend::mtp_status,
|
||||||
mtp_backend::mtp_store_credentials,
|
mtp_backend::mtp_store_credentials,
|
||||||
mtp_backend::mtp_has_credentials,
|
mtp_backend::mtp_has_credentials,
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,12 @@ use base64::{
|
||||||
Engine as _,
|
Engine as _,
|
||||||
};
|
};
|
||||||
use mtp::client::{ClientConfig, MTPClient, MTPConnection, Policy, SendMode};
|
use mtp::client::{ClientConfig, MTPClient, MTPConnection, Policy, SendMode};
|
||||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataValue, TypeMap};
|
use mtp::codec::{
|
||||||
|
CommunicationType, CommunicationValue, DataType, DataValue, SealedRelayBuilder, TypeMap,
|
||||||
|
};
|
||||||
use mtp::crypto::{
|
use mtp::crypto::{
|
||||||
derive_encryption_key, AeadDecrypt, ChaCha20Poly1305, HybridKem, Keyring, PublicKeyBundle,
|
derive_encryption_key, AeadDecrypt, ChaCha20Poly1305, DualSigner, HybridKem, Keyring,
|
||||||
|
PublicKeyBundle,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
|
|
@ -28,6 +31,9 @@ const CHAT_SECRET_SCHEME: &str = "mtp-chat-secret-kem-chacha20poly1305-hkdf-sha2
|
||||||
const INITIAL_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
|
const INITIAL_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
const MAX_BUFFERED_INITIAL_FRAMES: usize = 1_000;
|
const MAX_BUFFERED_INITIAL_FRAMES: usize = 1_000;
|
||||||
const NOTIFICATION_QUEUE_CAPACITY: usize = 32;
|
const NOTIFICATION_QUEUE_CAPACITY: usize = 32;
|
||||||
|
const ROUTE_TARGET_ID_MASK: u64 = (1_u64 << 48) - 1;
|
||||||
|
const USER_ROUTE_TARGET_KIND: u64 = 0x4000_0000_0000_0000;
|
||||||
|
const IOTA_ROUTE_TARGET_KIND: u64 = 0x8000_0000_0000_0000;
|
||||||
#[cfg(target_os = "android")]
|
#[cfg(target_os = "android")]
|
||||||
const ROOT_YE_PEM: &[u8] = b"-----BEGIN CERTIFICATE-----\n\
|
const ROOT_YE_PEM: &[u8] = b"-----BEGIN CERTIFICATE-----\n\
|
||||||
MIIB2TCCAWCgAwIBAgIRAKQCa6LvbHwg1AR+XmWmk4AwCgYIKoZIzj0EAwMwLjEL\n\
|
MIIB2TCCAWCgAwIBAgIRAKQCa6LvbHwg1AR+XmWmk4AwCgYIKoZIzj0EAwMwLjEL\n\
|
||||||
|
|
@ -79,6 +85,44 @@ pub struct MtpSnapshot {
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct EncodedKeyMaterial {
|
||||||
|
value: String,
|
||||||
|
encoding: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||||
|
enum RelayTargetDto {
|
||||||
|
User { id: u64 },
|
||||||
|
Iota { id: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RelayTargetDto {
|
||||||
|
fn wire_id(self) -> Result<u64, String> {
|
||||||
|
let (kind, id) = match self {
|
||||||
|
Self::User { id } => (USER_ROUTE_TARGET_KIND, id),
|
||||||
|
Self::Iota { id } => (IOTA_ROUTE_TARGET_KIND, id),
|
||||||
|
};
|
||||||
|
if id == 0 || id > ROUTE_TARGET_ID_MASK {
|
||||||
|
return Err("relay target ID must be a non-zero 48-bit integer".into());
|
||||||
|
}
|
||||||
|
Ok(kind | id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct SealedRelayRequest {
|
||||||
|
type_name: String,
|
||||||
|
data: Value,
|
||||||
|
next_hop: RelayTargetDto,
|
||||||
|
final_recipient_id: u64,
|
||||||
|
metadata_recipients: Vec<EncodedKeyMaterial>,
|
||||||
|
content_recipients: Vec<EncodedKeyMaterial>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
#[derive(Clone, Serialize)]
|
||||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||||
enum MtpEvent {
|
enum MtpEvent {
|
||||||
|
|
@ -695,6 +739,88 @@ async fn resolve_endpoint(config: &MtpConfig) -> Result<(String, String), String
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn decode_key_material(value: EncodedKeyMaterial) -> Result<PublicKeyBundle, String> {
|
||||||
|
let bytes = match value.encoding.as_str() {
|
||||||
|
"base64" => decode_browser_base64(&value.value)?,
|
||||||
|
"hex" => decode_sdk_bytes(&value.value)?,
|
||||||
|
encoding => return Err(format!("unsupported key material encoding: {encoding}")),
|
||||||
|
};
|
||||||
|
let key = PublicKeyBundle::from_bytes(&bytes)
|
||||||
|
.map_err(|error| format!("invalid relay recipient public key: {error}"))?;
|
||||||
|
key.validate()
|
||||||
|
.map_err(|error| format!("invalid relay recipient public key: {error}"))?;
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_sealed_relay(request: SealedRelayRequest) -> Result<Value, String> {
|
||||||
|
if request.metadata_recipients.is_empty() || request.content_recipients.is_empty() {
|
||||||
|
return Err("sealed relay requires metadata and content recipients".into());
|
||||||
|
}
|
||||||
|
if request.final_recipient_id == 0 {
|
||||||
|
return Err("sealed relay final recipient ID must be non-zero".into());
|
||||||
|
}
|
||||||
|
let manager = manager();
|
||||||
|
let connection = manager
|
||||||
|
.connection
|
||||||
|
.read()
|
||||||
|
.map_err(|_| "MTP connection lock is unavailable")?
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| "MTP is not connected".to_string())?;
|
||||||
|
let config = manager
|
||||||
|
.config
|
||||||
|
.read()
|
||||||
|
.map_err(|_| "MTP configuration lock is unavailable")?
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| "MTP credentials are unavailable".to_string())?;
|
||||||
|
let keyring_bytes = decode_browser_base64(&config.keyring)?;
|
||||||
|
let keyring = Keyring::from_bytes(&keyring_bytes)
|
||||||
|
.map_err(|error| format!("invalid MTP keyring: {error}"))?;
|
||||||
|
let signer = DualSigner::new(
|
||||||
|
&keyring.sig_cl_secret_key,
|
||||||
|
&keyring.sig_pq_secret_key,
|
||||||
|
&keyring.sig_pq_public_key,
|
||||||
|
)
|
||||||
|
.map_err(|error| format!("invalid MTP signing key: {error}"))?;
|
||||||
|
let next_hop_id = request.next_hop.wire_id()?;
|
||||||
|
let type_map = TypeMap::latest();
|
||||||
|
let content = json_to_frame(&request.type_name, request.data, 1)?.into_payload();
|
||||||
|
let metadata_recipients = request
|
||||||
|
.metadata_recipients
|
||||||
|
.into_iter()
|
||||||
|
.map(decode_key_material)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let content_recipients = request
|
||||||
|
.content_recipients
|
||||||
|
.into_iter()
|
||||||
|
.map(decode_key_material)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let created_at = mtp::common::unix_time_millis()
|
||||||
|
.map_err(|error| format!("failed to get relay timestamp: {error}"))?;
|
||||||
|
let request_id = connection.next_request_id().await?;
|
||||||
|
let message_id = format!("tensamin-relay-{created_at}-{request_id}");
|
||||||
|
let frame = SealedRelayBuilder::new(
|
||||||
|
request.type_name,
|
||||||
|
content,
|
||||||
|
config.user_id,
|
||||||
|
request.final_recipient_id,
|
||||||
|
next_hop_id,
|
||||||
|
&signer,
|
||||||
|
)
|
||||||
|
.message_id(message_id)
|
||||||
|
.created_at(created_at)
|
||||||
|
.metadata_recipients(metadata_recipients)
|
||||||
|
.content_recipients(content_recipients)
|
||||||
|
.type_map(&type_map)
|
||||||
|
.build()
|
||||||
|
.map_err(|error| format!("failed to build sealed relay: {error}"))?;
|
||||||
|
let response = connection
|
||||||
|
.mtp
|
||||||
|
.request(&frame, None)
|
||||||
|
.await
|
||||||
|
.map_err(|error| format!("sealed relay request failed: {error}"))?;
|
||||||
|
frame_to_json(&response)
|
||||||
|
}
|
||||||
|
|
||||||
async fn handle_push(
|
async fn handle_push(
|
||||||
generation: u64,
|
generation: u64,
|
||||||
notification_tx: &mpsc::Sender<CommunicationValue>,
|
notification_tx: &mpsc::Sender<CommunicationValue>,
|
||||||
|
|
@ -1047,7 +1173,8 @@ mod tests {
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
container_value_by_name, decode_browser_base64, decode_sdk_bytes, frame_to_json,
|
container_value_by_name, decode_browser_base64, decode_sdk_bytes, frame_to_json,
|
||||||
jittered_retry_delay, json_to_frame, prepare_initial_state_ack, RequestIdAllocator,
|
jittered_retry_delay, json_to_frame, prepare_initial_state_ack, RelayTargetDto,
|
||||||
|
RequestIdAllocator,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -1070,6 +1197,20 @@ mod tests {
|
||||||
assert_eq!(ids.next().unwrap(), 2);
|
assert_eq!(ids.next().unwrap(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn iota_relay_target_encodes_its_namespace() {
|
||||||
|
assert_eq!(
|
||||||
|
RelayTargetDto::Iota { id: 42 }.wire_id().unwrap(),
|
||||||
|
0x8000_0000_0000_002a
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn relay_target_rejects_raw_or_out_of_range_ids() {
|
||||||
|
assert!(RelayTargetDto::Iota { id: 0 }.wire_id().is_err());
|
||||||
|
assert!(RelayTargetDto::User { id: 1_u64 << 48 }.wire_id().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn retry_jitter_stays_within_policy_bounds() {
|
fn retry_jitter_stays_within_policy_bounds() {
|
||||||
let delay = jittered_retry_delay(std::time::Duration::from_secs(10));
|
let delay = jittered_retry_delay(std::time::Duration::from_secs(10));
|
||||||
|
|
@ -1194,6 +1335,11 @@ pub async fn mtp_request(type_name: String, data: Value) -> Result<Value, String
|
||||||
manager().request(&type_name, data).await
|
manager().request(&type_name, data).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mtp_send_sealed_relay(request: SealedRelayRequest) -> Result<Value, String> {
|
||||||
|
send_sealed_relay(request).await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn mtp_status() -> MtpSnapshot {
|
pub fn mtp_status() -> MtpSnapshot {
|
||||||
manager().snapshot()
|
manager().snapshot()
|
||||||
|
|
|
||||||
1
apps/web/.gitignore
vendored
1
apps/web/.gitignore
vendored
|
|
@ -8,6 +8,7 @@ pnpm-debug.log*
|
||||||
lerna-debug.log*
|
lerna-debug.log*
|
||||||
|
|
||||||
node_modules
|
node_modules
|
||||||
|
.mtp
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,9 @@ import {
|
||||||
useIsMobile,
|
useIsMobile,
|
||||||
} from "@methanium/ui";
|
} from "@methanium/ui";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
import { useMTP } from "@tensamin/mtp";
|
import { MTPProtocolError } from "mtp";
|
||||||
|
import { RelayRejectedError, requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||||
|
import { log } from "@tensamin/shared/log";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { isTauri } from "@tauri-apps/api/core";
|
import { isTauri } from "@tauri-apps/api/core";
|
||||||
|
|
@ -51,8 +53,9 @@ export default function Page() {
|
||||||
|
|
||||||
// Add Conversation Button Component
|
// Add Conversation Button Component
|
||||||
function AddConversationButton() {
|
function AddConversationButton() {
|
||||||
const { send } = useMTP();
|
const { send, sendSealedRelay } = useMTP();
|
||||||
const { contacts, insertContact } = useSession();
|
const { contacts, insertContact } = useSession();
|
||||||
|
const { load } = useStorage();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
@ -64,7 +67,7 @@ function AddConversationButton() {
|
||||||
// username check
|
// username check
|
||||||
const schema = z
|
const schema = z
|
||||||
.string()
|
.string()
|
||||||
.min(1, "Username is too short")
|
.regex(/^[a-z0-9]+$/, "Username must use lowercase letters and numbers")
|
||||||
.max(15, "Username is too long");
|
.max(15, "Username is too long");
|
||||||
|
|
||||||
const result = schema.safeParse(username?.toLowerCase().trim());
|
const result = schema.safeParse(username?.toLowerCase().trim());
|
||||||
|
|
@ -74,22 +77,27 @@ function AddConversationButton() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// user existence check
|
let user;
|
||||||
const user = await send("GetUserData", {
|
try {
|
||||||
Username: result.data,
|
user = await send("GetUserData", { Username: result.data });
|
||||||
})
|
} catch (error) {
|
||||||
.then((data) => {
|
if (error instanceof MTPProtocolError && error.type === "ErrorNotFound") {
|
||||||
if (data.type === "ErrorNotFound" || data.data.UserId === 0) {
|
setError("User not found");
|
||||||
throw new Error();
|
} else if (error instanceof MTPProtocolError) {
|
||||||
|
setError(`User lookup failed: ${error.type}`);
|
||||||
|
} else {
|
||||||
|
setError("User lookup failed: connection error");
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
return data;
|
}
|
||||||
})
|
if (user.type === "ErrorNotFound") {
|
||||||
.catch(() => {
|
|
||||||
setError("User not found");
|
setError("User not found");
|
||||||
return;
|
return;
|
||||||
});
|
}
|
||||||
if (!user) return;
|
if (user.type !== "GetUserData") {
|
||||||
|
setError(`User lookup failed: ${user.type}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// alrady added check
|
// alrady added check
|
||||||
if (contacts.some((contact) => contact.UserId === user.data.UserId)) {
|
if (contacts.some((contact) => contact.UserId === user.data.UserId)) {
|
||||||
|
|
@ -100,25 +108,44 @@ function AddConversationButton() {
|
||||||
// add the conv
|
// add the conv
|
||||||
const timeout = setTimeout(() => setLoading(true), 500);
|
const timeout = setTimeout(() => setLoading(true), 500);
|
||||||
|
|
||||||
send("AddConversation", {
|
try {
|
||||||
ChatPartnerId: user.data.UserId,
|
const userId = await load("user_id");
|
||||||
})
|
const iota = await send("GetIotaData", { UserId: userId });
|
||||||
.then(() => {
|
if (iota.type !== "GetIotaData") {
|
||||||
insertContact(user.data.UserId);
|
setError(`Iota lookup failed: ${iota.type}`);
|
||||||
setOpen(false);
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
if (String(error).includes("error_not_found")) {
|
|
||||||
setError("User not found");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const response = await sendSealedRelay(
|
||||||
setError(String(error));
|
"AddConversation",
|
||||||
})
|
{ ChatPartnerId: user.data.UserId },
|
||||||
.finally(() => {
|
{
|
||||||
|
nextHop: { kind: "iota", id: iota.data.IotaId },
|
||||||
|
finalRecipientId: userId,
|
||||||
|
metadataRecipients: [
|
||||||
|
{ value: iota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
contentRecipients: [
|
||||||
|
{ value: iota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
requireRelaySuccess(response);
|
||||||
|
insertContact(user.data.UserId);
|
||||||
|
setOpen(false);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof RelayRejectedError) {
|
||||||
|
setError(
|
||||||
|
`Could not route the request to your Iota: ${error.responseType}`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
log(1, "mtp", "red", "Add conversation failed", error);
|
||||||
|
const detail = error instanceof Error ? error.message : "unknown error";
|
||||||
|
setError(`Add conversation failed: ${detail}`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -129,7 +129,10 @@ export default defineConfig({
|
||||||
...tensaminPwa(),
|
...tensaminPwa(),
|
||||||
methaniumUi({ defaultThemeId: "tensamin" }),
|
methaniumUi({ defaultThemeId: "tensamin" }),
|
||||||
deepFilterAssetHeaders(resolve(appDir, "public")),
|
deepFilterAssetHeaders(resolve(appDir, "public")),
|
||||||
mtp({ typeMaps: resolve(appDir, "../../mtp-type-maps/type-maps.yaml") }),
|
mtp({
|
||||||
|
typeMaps: resolve(appDir, "../../mtp-type-maps/type-maps.yaml"),
|
||||||
|
outDir: ".mtp",
|
||||||
|
}),
|
||||||
{
|
{
|
||||||
name: "workspace-realpath-resolution",
|
name: "workspace-realpath-resolution",
|
||||||
enforce: "post",
|
enforce: "post",
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import { Button } from "@methanium/ui";
|
||||||
|
|
||||||
import { Plus, Laugh, FileVideo, SendHorizonal } from "lucide-react";
|
import { Plus, Laugh, FileVideo, SendHorizonal } from "lucide-react";
|
||||||
import { useChat, useReplyMessage } from "../context";
|
import { useChat, useReplyMessage } from "../context";
|
||||||
import { useMTP } from "@tensamin/mtp";
|
import { requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||||
import { log, toast } from "@tensamin/shared/log";
|
import { log, toast } from "@tensamin/shared/log";
|
||||||
import { cn, useIsMobile } from "@methanium/ui";
|
import { cn, useIsMobile } from "@methanium/ui";
|
||||||
import { encryptChatText } from "@tensamin/crypto/chatSecret";
|
import { encryptChatText } from "@tensamin/crypto/chatSecret";
|
||||||
|
|
@ -39,7 +39,7 @@ export default function InputComponent({
|
||||||
}) {
|
}) {
|
||||||
const [invertEnterBehavior, setInvertEnterBehavior] = useState(false);
|
const [invertEnterBehavior, setInvertEnterBehavior] = useState(false);
|
||||||
|
|
||||||
const { send } = useMTP();
|
const { send, sendSealedRelay } = useMTP();
|
||||||
const {
|
const {
|
||||||
addLiveMessage,
|
addLiveMessage,
|
||||||
chatSecret,
|
chatSecret,
|
||||||
|
|
@ -174,19 +174,46 @@ export default function InputComponent({
|
||||||
|
|
||||||
log(3, "chat", "purple", "Content encrypted, sending message...");
|
log(3, "chat", "purple", "Content encrypted, sending message...");
|
||||||
|
|
||||||
send("MessageSend", {
|
try {
|
||||||
|
const [ownIota, peerIota] = await Promise.all([
|
||||||
|
send("GetIotaData", { UserId: ownId }),
|
||||||
|
send("GetIotaData", { UserId: userId }),
|
||||||
|
]);
|
||||||
|
if (ownIota.type !== "GetIotaData" || peerIota.type !== "GetIotaData") {
|
||||||
|
throw new Error("Could not resolve an Iota for this message");
|
||||||
|
}
|
||||||
|
const response = await sendSealedRelay(
|
||||||
|
"MessageSend",
|
||||||
|
{
|
||||||
Content: encryptedContent,
|
Content: encryptedContent,
|
||||||
ReceiverId: userId,
|
ReceiverId: userId,
|
||||||
SendTime: time,
|
SendTime: time,
|
||||||
...(replyTo && { ReplyId: replyTo }),
|
...(replyTo && { ReplyId: replyTo }),
|
||||||
}).catch((e) => {
|
},
|
||||||
|
{
|
||||||
|
nextHop: { kind: "iota", id: ownIota.data.IotaId },
|
||||||
|
finalRecipientId: userId,
|
||||||
|
metadataRecipients: [
|
||||||
|
{ value: ownIota.data.PublicKey, encoding: "base64" },
|
||||||
|
{ value: peerIota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
contentRecipients: [
|
||||||
|
{ value: ownIota.data.PublicKey, encoding: "base64" },
|
||||||
|
{ value: peerIota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
requireRelaySuccess(response);
|
||||||
|
reference.setMessageState("sent");
|
||||||
|
} catch (e) {
|
||||||
log(0, "Chat", "red", "Failed to send message", e, {
|
log(0, "Chat", "red", "Failed to send message", e, {
|
||||||
ReceiverId: userId,
|
ReceiverId: userId,
|
||||||
SendTime: time,
|
SendTime: time,
|
||||||
});
|
});
|
||||||
reference.setFailed(true);
|
reference.setFailed(true);
|
||||||
toast("error", "Failed to send message");
|
toast("error", "Failed to send message");
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (replyTo) {
|
if (replyTo) {
|
||||||
setReplyTo(undefined);
|
setReplyTo(undefined);
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ import {
|
||||||
wrapChatSecret,
|
wrapChatSecret,
|
||||||
} from "@tensamin/crypto/chatSecret";
|
} from "@tensamin/crypto/chatSecret";
|
||||||
import { useStorage } from "@tensamin/storage/context";
|
import { useStorage } from "@tensamin/storage/context";
|
||||||
import { useMTP } from "@tensamin/mtp";
|
import { requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||||
import { log, toast } from "@tensamin/shared/log";
|
import { log, toast } from "@tensamin/shared/log";
|
||||||
import { useSession } from "@tensamin/storage/session";
|
import { useSession } from "@tensamin/storage/session";
|
||||||
import { useUser } from "@tensamin/user/context";
|
import { useUser } from "@tensamin/user/context";
|
||||||
|
|
@ -226,7 +226,7 @@ export async function fetchReplyMessage({
|
||||||
|
|
||||||
export default function Provider({ children }: { children: ReactNode }) {
|
export default function Provider({ children }: { children: ReactNode }) {
|
||||||
const { load } = useStorage();
|
const { load } = useStorage();
|
||||||
const { send, subscribe } = useMTP();
|
const { send, sendSealedRelay, subscribe } = useMTP();
|
||||||
const { get: getUser } = useUser();
|
const { get: getUser } = useUser();
|
||||||
const { moveUserIdToTop } = useSession();
|
const { moveUserIdToTop } = useSession();
|
||||||
|
|
||||||
|
|
@ -469,9 +469,17 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
version: CHAT_SECRET_VERSION,
|
version: CHAT_SECRET_VERSION,
|
||||||
});
|
});
|
||||||
|
|
||||||
assertProtocolSuccess(
|
const ownIota = await send("GetIotaData", { UserId: ownUserId });
|
||||||
|
if (ownIota.type !== "GetIotaData") {
|
||||||
|
throw new Error(`Own Iota lookup failed: ${ownIota.type}`);
|
||||||
|
}
|
||||||
|
const peerIota = await send("GetIotaData", { UserId: userIdValue });
|
||||||
|
if (peerIota.type !== "GetIotaData") {
|
||||||
|
throw new Error(`Peer Iota lookup failed: ${peerIota.type}`);
|
||||||
|
}
|
||||||
|
const response = await sendSealedRelay(
|
||||||
"SetChatSecret",
|
"SetChatSecret",
|
||||||
await send("SetChatSecret", {
|
{
|
||||||
ChatId: chatId,
|
ChatId: chatId,
|
||||||
SecretId: secretId,
|
SecretId: secretId,
|
||||||
VersionNumber: CHAT_SECRET_VERSION,
|
VersionNumber: CHAT_SECRET_VERSION,
|
||||||
|
|
@ -489,8 +497,21 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
KemCiphertext: protocolBytes(peerWrapped.kemCiphertext),
|
KemCiphertext: protocolBytes(peerWrapped.kemCiphertext),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}),
|
},
|
||||||
|
{
|
||||||
|
nextHop: { kind: "iota", id: ownIota.data.IotaId },
|
||||||
|
finalRecipientId: userIdValue,
|
||||||
|
metadataRecipients: [
|
||||||
|
{ value: ownIota.data.PublicKey, encoding: "base64" },
|
||||||
|
{ value: peerIota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
contentRecipients: [
|
||||||
|
{ value: ownIota.data.PublicKey, encoding: "base64" },
|
||||||
|
{ value: peerIota.data.PublicKey, encoding: "base64" },
|
||||||
|
],
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
requireRelaySuccess(response);
|
||||||
|
|
||||||
if (active) {
|
if (active) {
|
||||||
setCurrentChatSecretState({ userId: userIdValue, value: rawSecret });
|
setCurrentChatSecretState({ userId: userIdValue, value: rawSecret });
|
||||||
|
|
@ -508,7 +529,7 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
active = false;
|
||||||
};
|
};
|
||||||
}, [getUser, load, send, userIdValue]);
|
}, [getUser, load, send, sendSealedRelay, userIdValue]);
|
||||||
|
|
||||||
const getChatSecret = useCallback(
|
const getChatSecret = useCallback(
|
||||||
async (userId: number): Promise<Uint8Array | null> => {
|
async (userId: number): Promise<Uint8Array | null> => {
|
||||||
|
|
@ -901,6 +922,9 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
setFailed: (failed: boolean) => {
|
setFailed: (failed: boolean) => {
|
||||||
editMessage(message.SendTime, { failed });
|
editMessage(message.SendTime, { failed });
|
||||||
},
|
},
|
||||||
|
setMessageState: (MessageState: RawMessage["MessageState"]) => {
|
||||||
|
editMessage(message.SendTime, { MessageState });
|
||||||
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
[editMessage, userIdValue, moveUserIdToTop, ownId],
|
[editMessage, userIdValue, moveUserIdToTop, ownId],
|
||||||
|
|
@ -1021,6 +1045,7 @@ type contextType = {
|
||||||
liveMessages: () => LiveMessage[];
|
liveMessages: () => LiveMessage[];
|
||||||
addLiveMessage: (message: RawMessage) => {
|
addLiveMessage: (message: RawMessage) => {
|
||||||
setFailed: (failed: boolean) => void;
|
setFailed: (failed: boolean) => void;
|
||||||
|
setMessageState: (messageState: RawMessage["MessageState"]) => void;
|
||||||
};
|
};
|
||||||
editMessage: (sendTime: number, edit: MessageEdit) => void;
|
editMessage: (sendTime: number, edit: MessageEdit) => void;
|
||||||
deleteMessage: (sendTime: number) => void;
|
deleteMessage: (sendTime: number) => void;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,11 @@
|
||||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { toast as sonnerToast } from "@methanium/ui";
|
import { toast as sonnerToast } from "@methanium/ui";
|
||||||
import { base64ToBytes, ConnectionState, MTPClient } from "mtp";
|
import {
|
||||||
|
base64ToBytes,
|
||||||
|
ConnectionState,
|
||||||
|
MTPClient,
|
||||||
|
MTPProtocolError,
|
||||||
|
} from "mtp";
|
||||||
import createAsyncQueue from "@tensamin/shared/asyncQueue";
|
import createAsyncQueue from "@tensamin/shared/asyncQueue";
|
||||||
import {
|
import {
|
||||||
mtp as mtpSchemas,
|
mtp as mtpSchemas,
|
||||||
|
|
@ -17,6 +22,8 @@ import {
|
||||||
type MTPContextType,
|
type MTPContextType,
|
||||||
type ProtocolMessage,
|
type ProtocolMessage,
|
||||||
removeMissingContacts,
|
removeMissingContacts,
|
||||||
|
sealedRelayResultFromFrame,
|
||||||
|
type SealedRelaySend,
|
||||||
useMessageHandlers,
|
useMessageHandlers,
|
||||||
} from "./mtpContext";
|
} from "./mtpContext";
|
||||||
import {
|
import {
|
||||||
|
|
@ -201,6 +208,23 @@ export function BrowserProvider(props: {
|
||||||
},
|
},
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
const sendSealedRelay: SealedRelaySend = useMemo(
|
||||||
|
() => async (type, data, options) => {
|
||||||
|
const client = clientRef.current;
|
||||||
|
if (!client) throw new Error("mtp is not connected");
|
||||||
|
try {
|
||||||
|
return sealedRelayResultFromFrame(
|
||||||
|
await client.requestSealedRelay(type, data, options),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof MTPProtocolError) {
|
||||||
|
return sealedRelayResultFromFrame(error.frame);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const resolveConnectionRef = useRef(() => {});
|
const resolveConnectionRef = useRef(() => {});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -338,6 +362,7 @@ export function BrowserProvider(props: {
|
||||||
hostPublicKey: { value: omikronPublicKey, encoding: "base64" },
|
hostPublicKey: { value: omikronPublicKey, encoding: "base64" },
|
||||||
descriptor: "client",
|
descriptor: "client",
|
||||||
pings: true,
|
pings: true,
|
||||||
|
securityProfile: { protectedSignatureSuite: "dual" },
|
||||||
logger: (event) => {
|
logger: (event) => {
|
||||||
if (event.type === "state") {
|
if (event.type === "state") {
|
||||||
if (generation !== connectionGeneration) return;
|
if (generation !== connectionGeneration) return;
|
||||||
|
|
@ -512,6 +537,7 @@ export function BrowserProvider(props: {
|
||||||
<MTPContext.Provider
|
<MTPContext.Provider
|
||||||
value={{
|
value={{
|
||||||
send: sendQueued,
|
send: sendQueued,
|
||||||
|
sendSealedRelay,
|
||||||
subscribe,
|
subscribe,
|
||||||
addInterceptor,
|
addInterceptor,
|
||||||
readyState,
|
readyState,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,12 @@
|
||||||
export { Provider, useMTP } from "./context";
|
export { Provider, useMTP } from "./context";
|
||||||
|
export { RelayRejectedError, requireRelaySuccess } from "./mtpContext";
|
||||||
export type {
|
export type {
|
||||||
BoundSendFn,
|
BoundSendFn,
|
||||||
MTPExchange,
|
MTPExchange,
|
||||||
MTPInterceptor,
|
MTPInterceptor,
|
||||||
ProtocolMessage,
|
ProtocolMessage,
|
||||||
|
RelayTarget,
|
||||||
|
SealedRelayOptions,
|
||||||
|
SealedRelayResult,
|
||||||
|
SealedRelaySend,
|
||||||
} from "./mtpContext";
|
} from "./mtpContext";
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
import { createContext, useCallback, useRef } from "react";
|
import { createContext, useCallback, useRef } from "react";
|
||||||
import type {
|
import type {
|
||||||
|
MTPDataValueInput,
|
||||||
|
MTPEncodedBytesInput,
|
||||||
|
MTPFrame,
|
||||||
MTPRequestFunction,
|
MTPRequestFunction,
|
||||||
MTPResponseFrame,
|
MTPResponseFrame,
|
||||||
MTPSubscriptionFunction,
|
MTPSubscriptionFunction,
|
||||||
|
|
@ -19,6 +22,56 @@ export type ProtocolMessage<
|
||||||
|
|
||||||
export type BoundSendFn = MTPRequestFunction<typeof mtpSchemas>;
|
export type BoundSendFn = MTPRequestFunction<typeof mtpSchemas>;
|
||||||
|
|
||||||
|
export type RelayTarget =
|
||||||
|
| { kind: "user"; id: number }
|
||||||
|
| { kind: "iota"; id: number };
|
||||||
|
|
||||||
|
export type SealedRelayOptions = {
|
||||||
|
nextHop: RelayTarget;
|
||||||
|
finalRecipientId: number;
|
||||||
|
metadataRecipients: MTPEncodedBytesInput[];
|
||||||
|
contentRecipients: MTPEncodedBytesInput[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SealedRelayResult = {
|
||||||
|
type: string;
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function sealedRelayResultFromFrame(frame: MTPFrame): SealedRelayResult {
|
||||||
|
return {
|
||||||
|
type: frame.type,
|
||||||
|
data:
|
||||||
|
typeof frame.data === "object" &&
|
||||||
|
frame.data !== null &&
|
||||||
|
!Array.isArray(frame.data)
|
||||||
|
? (frame.data as Record<string, unknown>)
|
||||||
|
: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RelayRejectedError extends Error {
|
||||||
|
public readonly responseType: string;
|
||||||
|
|
||||||
|
constructor(responseType: string) {
|
||||||
|
super(`Relay rejected with ${responseType}`);
|
||||||
|
this.responseType = responseType;
|
||||||
|
this.name = "RelayRejectedError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireRelaySuccess(response: SealedRelayResult): void {
|
||||||
|
if (response.type !== "Success") {
|
||||||
|
throw new RelayRejectedError(response.type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SealedRelaySend = (
|
||||||
|
type: string,
|
||||||
|
data: MTPDataValueInput,
|
||||||
|
options: SealedRelayOptions,
|
||||||
|
) => Promise<SealedRelayResult>;
|
||||||
|
|
||||||
export type MTPExchange = {
|
export type MTPExchange = {
|
||||||
type: keyof typeof mtpSchemas & string;
|
type: keyof typeof mtpSchemas & string;
|
||||||
data: unknown;
|
data: unknown;
|
||||||
|
|
@ -29,6 +82,7 @@ export type MTPInterceptor = (exchange: MTPExchange) => void | Promise<void>;
|
||||||
|
|
||||||
export type MTPContextType = {
|
export type MTPContextType = {
|
||||||
send: BoundSendFn;
|
send: BoundSendFn;
|
||||||
|
sendSealedRelay: SealedRelaySend;
|
||||||
subscribe: MTPSubscriptionFunction<typeof mtpSchemas>;
|
subscribe: MTPSubscriptionFunction<typeof mtpSchemas>;
|
||||||
addInterceptor: (interceptor: MTPInterceptor) => () => void;
|
addInterceptor: (interceptor: MTPInterceptor) => () => void;
|
||||||
readyState: number;
|
readyState: number;
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,8 @@ import {
|
||||||
MTPContext,
|
MTPContext,
|
||||||
type ProtocolMessage,
|
type ProtocolMessage,
|
||||||
removeMissingContacts,
|
removeMissingContacts,
|
||||||
|
type SealedRelayResult,
|
||||||
|
type SealedRelaySend,
|
||||||
useMessageHandlers,
|
useMessageHandlers,
|
||||||
} from "./mtpContext";
|
} from "./mtpContext";
|
||||||
|
|
||||||
|
|
@ -233,12 +235,26 @@ export function TauriProvider(props: {
|
||||||
},
|
},
|
||||||
[connection, interceptorsRef],
|
[connection, interceptorsRef],
|
||||||
);
|
);
|
||||||
|
const sendSealedRelay = useCallback<SealedRelaySend>(
|
||||||
|
async (type, data, options) => {
|
||||||
|
return invoke<SealedRelayResult>("mtp_send_sealed_relay", {
|
||||||
|
typeName: type,
|
||||||
|
data,
|
||||||
|
nextHop: options.nextHop,
|
||||||
|
finalRecipientId: options.finalRecipientId,
|
||||||
|
metadataRecipients: options.metadataRecipients,
|
||||||
|
contentRecipients: options.contentRecipients,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
const connected = snapshot.readyState === ConnectionState.Connected;
|
const connected = snapshot.readyState === ConnectionState.Connected;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MTPContext.Provider
|
<MTPContext.Provider
|
||||||
value={{
|
value={{
|
||||||
send,
|
send,
|
||||||
|
sendSealedRelay,
|
||||||
subscribe,
|
subscribe,
|
||||||
addInterceptor,
|
addInterceptor,
|
||||||
readyState: snapshot.readyState,
|
readyState: snapshot.readyState,
|
||||||
|
|
|
||||||
|
|
@ -148,7 +148,7 @@ const userFields = {
|
||||||
About: z.string().max(255).optional(),
|
About: z.string().max(255).optional(),
|
||||||
Avatar: z.string().optional(),
|
Avatar: z.string().optional(),
|
||||||
Display: z.string().min(1).max(15),
|
Display: z.string().min(1).max(15),
|
||||||
IotaId: z.number(),
|
IotaId: z.number().optional(),
|
||||||
OmikronConnections: z.array(z.number()),
|
OmikronConnections: z.array(z.number()),
|
||||||
OmikronId: z.number().optional(),
|
OmikronId: z.number().optional(),
|
||||||
PublicKey: z.base64(),
|
PublicKey: z.base64(),
|
||||||
|
|
@ -240,6 +240,27 @@ export const mtp = {
|
||||||
}),
|
}),
|
||||||
response: userSchema,
|
response: userSchema,
|
||||||
},
|
},
|
||||||
|
GetIotaData: {
|
||||||
|
request: z
|
||||||
|
.object({
|
||||||
|
IotaId: z.number().int().positive().optional(),
|
||||||
|
UserId: z.number().int().positive().optional(),
|
||||||
|
Username: z.string().min(1).max(15).optional(),
|
||||||
|
})
|
||||||
|
.refine(
|
||||||
|
({ IotaId, UserId, Username }) =>
|
||||||
|
[IotaId, UserId, Username].filter((value) => value !== undefined)
|
||||||
|
.length === 1,
|
||||||
|
"GetIotaData requires exactly one selector",
|
||||||
|
),
|
||||||
|
response: z.object({
|
||||||
|
IotaId: z.number().int().positive(),
|
||||||
|
PublicKey: z.base64(),
|
||||||
|
OmikronConnections: z.array(z.number().int().positive()).optional(),
|
||||||
|
UserId: z.number().int().positive().optional(),
|
||||||
|
Username: z.string().optional(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
GetStates: {
|
GetStates: {
|
||||||
request: z.object({
|
request: z.object({
|
||||||
SessionId: z.number().int().positive(),
|
SessionId: z.number().int().positive(),
|
||||||
|
|
|
||||||
987
pnpm-lock.yaml
generated
987
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
|
|
@ -7,4 +7,4 @@ allowBuilds:
|
||||||
esbuild: true
|
esbuild: true
|
||||||
overrides:
|
overrides:
|
||||||
"@methanium/ui": "https://git.methanium.net/methanium/ui/releases/download/0.0.29/methanium-ui.tgz"
|
"@methanium/ui": "https://git.methanium.net/methanium/ui/releases/download/0.0.29/methanium-ui.tgz"
|
||||||
mtp: "https://git.methanium.net/methanium/mtp/releases/download/0.3.0-dev-c7c7afe/mtp-0.3.0.tgz"
|
mtp: "link:../../../mtp"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue