Compare commits
2
Commits
master
..
905a339e3e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
905a339e3e | ||
|
|
6ce20927ee |
@@ -39,9 +39,8 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Rust nightly
|
- name: Install Rust nightly
|
||||||
uses: dtolnay/rust-toolchain@master
|
uses: dtolnay/rust-toolchain@nightly
|
||||||
with:
|
with:
|
||||||
toolchain: nightly-2026-10-31
|
|
||||||
targets: wasm32-unknown-unknown
|
targets: wasm32-unknown-unknown
|
||||||
components: llvm-tools-preview
|
components: llvm-tools-preview
|
||||||
|
|
||||||
@@ -52,4 +51,4 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CC_wasm32_unknown_unknown: clang
|
CC_wasm32_unknown_unknown: clang
|
||||||
AR_wasm32_unknown_unknown: llvm-ar
|
AR_wasm32_unknown_unknown: llvm-ar
|
||||||
run: cargo +nightly-2026-10-31 check -p coop_web --target wasm32-unknown-unknown
|
run: cargo +nightly check -p coop_web --target wasm32-unknown-unknown
|
||||||
|
|||||||
+1
-24
@@ -947,11 +947,7 @@ async fn extract_rumor(
|
|||||||
let Some(device_signer) = device_signer else {
|
let Some(device_signer) = device_signer else {
|
||||||
return Err(error);
|
return Err(error);
|
||||||
};
|
};
|
||||||
match try_unwrap_with(device_signer, gift_wrap).await {
|
try_unwrap_with(device_signer, gift_wrap).await?
|
||||||
Ok(unwrapped) => unwrapped,
|
|
||||||
// The wrap may be sealed to a key retired by a rotation
|
|
||||||
Err(_) => try_unwrap_archived(client, signer, gift_wrap).await?,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mut rumor = unwrapped.rumor;
|
let mut rumor = unwrapped.rumor;
|
||||||
@@ -1007,25 +1003,6 @@ async fn try_unwrap_with(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unwrap with an encryption key retired by a rotation; peers may still seal
|
|
||||||
/// to the previous key until their announcement cache refreshes
|
|
||||||
async fn try_unwrap_archived(
|
|
||||||
client: &Client,
|
|
||||||
signer: &UniversalSigner,
|
|
||||||
gift_wrap: &Event,
|
|
||||||
) -> Result<UnwrappedGift, Error> {
|
|
||||||
for keys in DeviceRegistry::archived_keys(client, signer).await? {
|
|
||||||
let archived = UniversalSigner::new(keys);
|
|
||||||
if let Ok(unwrapped) = try_unwrap_with(&archived, gift_wrap).await {
|
|
||||||
return Ok(unwrapped);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(anyhow!(
|
|
||||||
"No archived encryption key could unwrap the gift wrap"
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores an unwrapped event in local database with reference to original
|
/// Stores an unwrapped event in local database with reference to original
|
||||||
async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Result<(), Error> {
|
async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Result<(), Error> {
|
||||||
let room_id = rumor.uniq_id().to_string();
|
let room_id = rumor.uniq_id().to_string();
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ use crate::{FileAttachment, KIND_FILE_MESSAGE, NewMessage};
|
|||||||
|
|
||||||
const NO_DEKEY: &str = "User hasn't set up a decoupled encryption key yet.";
|
const NO_DEKEY: &str = "User hasn't set up a decoupled encryption key yet.";
|
||||||
const USER_NO_DEKEY: &str = "You haven't set up a decoupled encryption key yet. Set one up in the settings to message them.";
|
const USER_NO_DEKEY: &str = "You haven't set up a decoupled encryption key yet. Set one up in the settings to message them.";
|
||||||
const KEY_STALE: &str = "Your encryption key is out of date; sync it from another device in the settings to keep messaging.";
|
|
||||||
|
|
||||||
/// The outcome of delivering an encrypted rumor to a single receiver.
|
/// The outcome of delivering an encrypted rumor to a single receiver.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -554,7 +553,6 @@ impl Room {
|
|||||||
let config = self.config.clone();
|
let config = self.config.clone();
|
||||||
|
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
let resyncing = device.read(cx).is_resyncing();
|
|
||||||
let encryption_signer = device.read(cx).signer(cx);
|
let encryption_signer = device.read(cx).signer(cx);
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
@@ -576,28 +574,6 @@ impl Room {
|
|||||||
Some(cx.background_spawn(async move {
|
Some(cx.background_spawn(async move {
|
||||||
let signer_kind = config.signer_kind();
|
let signer_kind = config.signer_kind();
|
||||||
|
|
||||||
// Block sends while the local encryption key is stale against the
|
|
||||||
// current announcement; the replacement is being synced from
|
|
||||||
// another device
|
|
||||||
if resyncing && matches!(signer_kind, SignerKind::Auto | SignerKind::Encryption) {
|
|
||||||
let mut reports: Vec<SendReport> = receivers
|
|
||||||
.into_iter()
|
|
||||||
.map(|receiver| SendReport {
|
|
||||||
receiver: receiver.public_key(),
|
|
||||||
result: Err(KEY_STALE.into()),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if config.backup() {
|
|
||||||
reports.push(SendReport {
|
|
||||||
receiver: sender.public_key(),
|
|
||||||
result: Err(KEY_STALE.into()),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return reports;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deliver to every receiver concurrently
|
// Deliver to every receiver concurrently
|
||||||
let sends = receivers.into_iter().map(|receiver| {
|
let sends = receivers.into_iter().map(|receiver| {
|
||||||
deliver(
|
deliver(
|
||||||
|
|||||||
+14
-68
@@ -30,14 +30,14 @@ use person::{Directory, Person};
|
|||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use settings::{AppSettings, SignerKind};
|
use settings::{AppSettings, SignerKind};
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use speech::speaker::{END_GRACE, Speaker};
|
use speech::speaker::Speaker;
|
||||||
use state::{
|
use state::{
|
||||||
FileAttachment, LocalFile, NostrRegistry, PickedFile, download_and_decrypt_file, pick_file,
|
FileAttachment, LocalFile, NostrRegistry, PickedFile, download_and_decrypt_file, pick_file,
|
||||||
};
|
};
|
||||||
use ui::{
|
use ui::{
|
||||||
Avatar, COMPACT_REACTION_EMOJIS, IconName, MessageActions, MessageMedia, MessageRow,
|
Avatar, COMPACT_REACTION_EMOJIS, IconName, MessageActions, MessageMedia, MessageRow,
|
||||||
REACTION_EMOJIS, ReactionBar, RenderedText, ReplyPreview, RevealText, WelcomeMessage,
|
REACTION_EMOJIS, ReactionBar, RenderedText, ReplyPreview, WelcomeMessage, group_reactions,
|
||||||
group_reactions, opens_run, rendered_text,
|
opens_run, rendered_text,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::file::*;
|
use crate::file::*;
|
||||||
@@ -46,7 +46,8 @@ use crate::file::*;
|
|||||||
const PRIVATE_NOTICE: &str =
|
const PRIVATE_NOTICE: &str =
|
||||||
"This conversation is private. Only members can see each other's messages.";
|
"This conversation is private. Only members can see each other's messages.";
|
||||||
|
|
||||||
/// Regex matching strings that consist entirely of emoji characters.
|
/// Regex matching strings that consist entirely of emoji characters,
|
||||||
|
/// zero-width joiners, variation selectors, and keycap combiners.
|
||||||
static EMOJI_RE: LazyLock<Regex> =
|
static EMOJI_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"^[\p{Emoji}\u{200D}\u{FE0F}\u{20E3}]+$").unwrap());
|
LazyLock::new(|| Regex::new(r"^[\p{Emoji}\u{200D}\u{FE0F}\u{20E3}]+$").unwrap());
|
||||||
|
|
||||||
@@ -89,10 +90,6 @@ pub struct ChatPanel {
|
|||||||
speech_started: Option<instant::Instant>,
|
speech_started: Option<instant::Instant>,
|
||||||
/// Reads messages aloud
|
/// Reads messages aloud
|
||||||
speaker: Speaker,
|
speaker: Speaker,
|
||||||
/// The message being revealed in step with speech, with its estimated duration
|
|
||||||
speech_reveal: Option<(EventId, Duration)>,
|
|
||||||
/// Fallback reveal end for backends that cannot report utterance end
|
|
||||||
reveal_timeout: Option<Task<Result<(), Error>>>,
|
|
||||||
/// Subject input state
|
/// Subject input state
|
||||||
subject_input: Entity<InputState>,
|
subject_input: Entity<InputState>,
|
||||||
/// Subject bar visibility
|
/// Subject bar visibility
|
||||||
@@ -225,20 +222,6 @@ impl ChatPanel {
|
|||||||
this.get_messages(window, cx);
|
this.get_messages(window, cx);
|
||||||
});
|
});
|
||||||
|
|
||||||
// End the speech reveal when the utterance finishes ahead of its estimate
|
|
||||||
let speaker = Speaker::new();
|
|
||||||
let end_events = speaker.end_events();
|
|
||||||
let reveal_end_task = cx.spawn(async move |this, cx| {
|
|
||||||
while end_events.recv_async().await.is_ok() {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.speech_reveal = None;
|
|
||||||
cx.notify();
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
focus_handle: cx.focus_handle(),
|
focus_handle: cx.focus_handle(),
|
||||||
id,
|
id,
|
||||||
@@ -251,9 +234,7 @@ impl ChatPanel {
|
|||||||
input,
|
input,
|
||||||
speech,
|
speech,
|
||||||
speech_started: None,
|
speech_started: None,
|
||||||
speaker,
|
speaker: Speaker::new(),
|
||||||
speech_reveal: None,
|
|
||||||
reveal_timeout: None,
|
|
||||||
subject_input,
|
subject_input,
|
||||||
subject_bar,
|
subject_bar,
|
||||||
replies_to,
|
replies_to,
|
||||||
@@ -264,7 +245,7 @@ impl ChatPanel {
|
|||||||
reports_by_id,
|
reports_by_id,
|
||||||
uploading: false,
|
uploading: false,
|
||||||
subscriptions,
|
subscriptions,
|
||||||
tasks: vec![reveal_end_task],
|
tasks: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1193,15 +1174,6 @@ impl ChatPanel {
|
|||||||
nostr.read(cx).current_user(),
|
nostr.read(cx).current_user(),
|
||||||
));
|
));
|
||||||
|
|
||||||
let body = match self
|
|
||||||
.speech_reveal
|
|
||||||
.as_ref()
|
|
||||||
.filter(|(reveal_id, _)| *reveal_id == id)
|
|
||||||
{
|
|
||||||
Some((_, duration)) => RevealText::new(message.preview(), *duration).into_any_element(),
|
|
||||||
None => rendered_text,
|
|
||||||
};
|
|
||||||
|
|
||||||
MessageRow::new(ix)
|
MessageRow::new(ix)
|
||||||
.show_author(show_author)
|
.show_author(show_author)
|
||||||
.hide_avatar(hide_avatar)
|
.hide_avatar(hide_avatar)
|
||||||
@@ -1226,7 +1198,7 @@ impl ChatPanel {
|
|||||||
.when(has_replies, |this| {
|
.when(has_replies, |this| {
|
||||||
this.children(self.render_message_replies(replies, cx))
|
this.children(self.render_message_replies(replies, cx))
|
||||||
})
|
})
|
||||||
.when(message.file.is_none(), |this| this.child(body))
|
.when(message.file.is_none(), |this| this.child(rendered_text))
|
||||||
.child(MessageMedia::new(&message.media))
|
.child(MessageMedia::new(&message.media))
|
||||||
.when_some(message.file.as_ref(), |this, file| {
|
.when_some(message.file.as_ref(), |this, file| {
|
||||||
this.child(self.render_message_file(&id, file, cx))
|
this.child(self.render_message_file(&id, file, cx))
|
||||||
@@ -1459,6 +1431,7 @@ impl ChatPanel {
|
|||||||
|
|
||||||
let reply_id = *id;
|
let reply_id = *id;
|
||||||
let dropdown_id = *id;
|
let dropdown_id = *id;
|
||||||
|
let speech_id = *id;
|
||||||
let public_key = *public_key;
|
let public_key = *public_key;
|
||||||
|
|
||||||
let actions = actions.reply(cx.listener(move |this, _event, _window, cx| {
|
let actions = actions.reply(cx.listener(move |this, _event, _window, cx| {
|
||||||
@@ -1474,42 +1447,15 @@ impl ChatPanel {
|
|||||||
actions
|
actions
|
||||||
};
|
};
|
||||||
|
|
||||||
let speaking = self.speech_reveal.is_some();
|
let actions = actions.speech(cx.listener(move |this, _event, window, cx| {
|
||||||
let speech_id = *id;
|
|
||||||
|
|
||||||
let actions = actions.speech(
|
|
||||||
speaking,
|
|
||||||
cx.listener(move |this, _event, window, cx| {
|
|
||||||
let text = this.message(&speech_id).map(|message| message.preview());
|
let text = this.message(&speech_id).map(|message| message.preview());
|
||||||
|
|
||||||
if let Some(text) = text {
|
if let Some(text) = text
|
||||||
match this.speaker.speak(&text) {
|
&& let Err(error) = this.speaker.speak(&text)
|
||||||
Ok(duration) => {
|
{
|
||||||
this.speech_reveal = Some((speech_id, duration));
|
window.push_notification(Notification::error(error.to_string()), cx);
|
||||||
|
|
||||||
// Re-enable speaking when no end event ever arrives
|
|
||||||
let session = (speech_id, duration);
|
|
||||||
let timer = cx.background_executor().timer(duration + END_GRACE);
|
|
||||||
this.reveal_timeout = Some(cx.spawn(async move |this, cx| {
|
|
||||||
timer.await;
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
if this.speech_reveal.as_ref() == Some(&session) {
|
|
||||||
this.speech_reveal = None;
|
|
||||||
cx.notify();
|
|
||||||
}
|
}
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
}));
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
window.push_notification(Notification::error(error.to_string()), cx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
actions.dropdown(move |menu, _window, _cx| {
|
actions.dropdown(move |menu, _window, _cx| {
|
||||||
menu.menu("Copy author", Box::new(Command::Copy(public_key)))
|
menu.menu("Copy author", Box::new(Command::Copy(public_key)))
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ use settings::AppSettings;
|
|||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use speech::speaker::Speaker;
|
use speech::speaker::Speaker;
|
||||||
use state::{NostrRegistry, pick_file, upload_file};
|
use state::{NostrRegistry, pick_file, upload_file};
|
||||||
use ui::{Avatar, RenderedText, RevealText, WelcomeMessage, rendered_text};
|
use ui::{Avatar, RenderedText, WelcomeMessage, rendered_text};
|
||||||
use util::{attachment_name, display_name, opens_run, pin_label, report};
|
use util::{attachment_name, display_name, opens_run, pin_label, report};
|
||||||
|
|
||||||
mod details;
|
mod details;
|
||||||
@@ -323,10 +323,6 @@ pub struct GroupPanel {
|
|||||||
speech_started: Option<instant::Instant>,
|
speech_started: Option<instant::Instant>,
|
||||||
/// Reads messages aloud
|
/// Reads messages aloud
|
||||||
speaker: Speaker,
|
speaker: Speaker,
|
||||||
/// The message being revealed in step with speech, with its estimated duration
|
|
||||||
speech_reveal: Option<(EventId, Duration)>,
|
|
||||||
/// Fallback reveal end for backends that cannot report utterance end
|
|
||||||
reveal_timeout: Option<Task<Result<()>>>,
|
|
||||||
/// Uploaded, non-encrypted attachments waiting to be sent.
|
/// Uploaded, non-encrypted attachments waiting to be sent.
|
||||||
attachments: Vec<Url>,
|
attachments: Vec<Url>,
|
||||||
/// Whether an upload is in flight.
|
/// Whether an upload is in flight.
|
||||||
@@ -429,20 +425,6 @@ impl GroupPanel {
|
|||||||
this.track_participants(cx);
|
this.track_participants(cx);
|
||||||
});
|
});
|
||||||
|
|
||||||
// End the speech reveal when the utterance finishes ahead of its estimate
|
|
||||||
let speaker = Speaker::new();
|
|
||||||
let end_events = speaker.end_events();
|
|
||||||
let reveal_end_task = cx.spawn(async move |this, cx| {
|
|
||||||
while end_events.recv_async().await.is_ok() {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.speech_reveal = None;
|
|
||||||
cx.notify();
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
focus_handle: cx.focus_handle(),
|
focus_handle: cx.focus_handle(),
|
||||||
group: group.downgrade(),
|
group: group.downgrade(),
|
||||||
@@ -455,12 +437,10 @@ impl GroupPanel {
|
|||||||
input,
|
input,
|
||||||
speech,
|
speech,
|
||||||
speech_started: None,
|
speech_started: None,
|
||||||
speaker,
|
speaker: Speaker::new(),
|
||||||
speech_reveal: None,
|
|
||||||
reveal_timeout: None,
|
|
||||||
attachments: Vec::new(),
|
attachments: Vec::new(),
|
||||||
uploading: false,
|
uploading: false,
|
||||||
tasks: smallvec![reveal_end_task],
|
tasks: smallvec![],
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1043,13 +1023,7 @@ impl GroupPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let directory = self.directory.clone();
|
let directory = self.directory.clone();
|
||||||
|
|
||||||
let content = match self
|
let content = self
|
||||||
.speech_reveal
|
|
||||||
.as_ref()
|
|
||||||
.filter(|(reveal_id, _)| *reveal_id == message.id)
|
|
||||||
{
|
|
||||||
Some((_, duration)) => RevealText::new(message.preview(), *duration).into_any_element(),
|
|
||||||
None => self
|
|
||||||
.rendered_texts_by_id
|
.rendered_texts_by_id
|
||||||
.entry(message.id)
|
.entry(message.id)
|
||||||
.or_insert_with(|| {
|
.or_insert_with(|| {
|
||||||
@@ -1064,8 +1038,7 @@ impl GroupPanel {
|
|||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.element(ix.into(), window, cx),
|
.element(ix.into(), window, cx);
|
||||||
};
|
|
||||||
|
|
||||||
let admin = nostr
|
let admin = nostr
|
||||||
.read(cx)
|
.read(cx)
|
||||||
@@ -1086,7 +1059,6 @@ impl GroupPanel {
|
|||||||
panel: cx.weak_entity(),
|
panel: cx.weak_entity(),
|
||||||
admin,
|
admin,
|
||||||
pinned,
|
pinned,
|
||||||
speaking: self.speech_reveal.is_some(),
|
|
||||||
persons: self.directory.clone(),
|
persons: self.directory.clone(),
|
||||||
},
|
},
|
||||||
cx,
|
cx,
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ use nip29::{Activity, Group, Reaction};
|
|||||||
use nostr_sdk::prelude::{EventId, Kind};
|
use nostr_sdk::prelude::{EventId, Kind};
|
||||||
use person::Directory;
|
use person::Directory;
|
||||||
use settings::AppSettings;
|
use settings::AppSettings;
|
||||||
use speech::speaker::END_GRACE;
|
|
||||||
use state::NostrRegistry;
|
use state::NostrRegistry;
|
||||||
use ui::{
|
use ui::{
|
||||||
Avatar, MessageActions, MessageMedia, MessageRow, REACTION_EMOJIS, ReactionBar, ReplyPreview,
|
Avatar, MessageActions, MessageMedia, MessageRow, REACTION_EMOJIS, ReactionBar, ReplyPreview,
|
||||||
@@ -28,8 +27,6 @@ pub(crate) struct Actions {
|
|||||||
pub panel: WeakEntity<GroupPanel>,
|
pub panel: WeakEntity<GroupPanel>,
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
pub pinned: bool,
|
pub pinned: bool,
|
||||||
/// Whether a message is currently being spoken, disabling the speech buttons
|
|
||||||
pub speaking: bool,
|
|
||||||
pub persons: Entity<Directory>,
|
pub persons: Entity<Directory>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,40 +91,14 @@ pub(crate) fn render(
|
|||||||
let speech_panel = actions.panel;
|
let speech_panel = actions.panel;
|
||||||
let panel = speech_panel.clone();
|
let panel = speech_panel.clone();
|
||||||
let speech_text = message.preview();
|
let speech_text = message.preview();
|
||||||
let speech_id = message.id;
|
|
||||||
let speaking = actions.speaking;
|
|
||||||
|
|
||||||
let row = row.overlay(
|
let row = row.overlay(MessageActions::new().speech(move |_event, _window, cx| {
|
||||||
MessageActions::new().speech(speaking, move |_event, _window, cx| {
|
|
||||||
_ = speech_panel.update_in(cx, |panel, window, cx| {
|
_ = speech_panel.update_in(cx, |panel, window, cx| {
|
||||||
match panel.speaker.speak(&speech_text) {
|
if let Err(error) = panel.speaker.speak(&speech_text) {
|
||||||
Ok(duration) => {
|
window.push_notification(Notification::error(error.to_string()), cx);
|
||||||
panel.speech_reveal = Some((speech_id, duration));
|
|
||||||
|
|
||||||
let session = (speech_id, duration);
|
|
||||||
let timer = cx.background_executor().timer(duration + END_GRACE);
|
|
||||||
|
|
||||||
panel.reveal_timeout = Some(cx.spawn(async move |this, cx| {
|
|
||||||
timer.await;
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
if this.speech_reveal.as_ref() == Some(&session) {
|
|
||||||
this.speech_reveal = None;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
window.push_notification(Notification::error(error.to_string()), cx)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}),
|
}));
|
||||||
);
|
|
||||||
|
|
||||||
let custom = nostr
|
let custom = nostr
|
||||||
.read(cx)
|
.read(cx)
|
||||||
|
|||||||
+156
-479
@@ -1,10 +1,9 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::collections::{HashSet, VecDeque};
|
use std::collections::HashSet;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||||
use gpui::{
|
use gpui::{
|
||||||
@@ -17,14 +16,12 @@ use gpui_kit::component::notification::{Notification, NotificationType};
|
|||||||
use gpui_kit::component::{ActiveTheme, Disableable, Sizable, WindowExt, h_flex, v_flex};
|
use gpui_kit::component::{ActiveTheme, Disableable, Sizable, WindowExt, h_flex, v_flex};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::Directory;
|
use person::Directory;
|
||||||
use settings::{AppSettings, NIP4E_ROTATION_MAX_DAYS, NIP4E_ROTATION_MIN_DAYS};
|
use settings::AppSettings;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{Announcement, NostrRegistry, UniversalSigner, credentials};
|
use state::{Announcement, NostrRegistry, UniversalSigner, credentials};
|
||||||
use ui::Avatar;
|
use ui::Avatar;
|
||||||
|
|
||||||
mod storage;
|
const IDENTIFIER: &str = "coop:device";
|
||||||
|
|
||||||
use storage::{SECONDS_PER_DAY, archive_key, get_keys, load_device_keys, set_keys};
|
|
||||||
|
|
||||||
pub fn init(cx: &mut App) {
|
pub fn init(cx: &mut App) {
|
||||||
DeviceRegistry::set_global(cx.new(DeviceRegistry::new), cx);
|
DeviceRegistry::set_global(cx.new(DeviceRegistry::new), cx);
|
||||||
@@ -62,18 +59,10 @@ impl DeviceEvent {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct DeviceRegistry {
|
pub struct DeviceRegistry {
|
||||||
signer: Entity<Option<UniversalSigner>>,
|
signer: Entity<Option<UniversalSigner>>,
|
||||||
/// Ephemeral client key for the in-flight key request; never persisted
|
/// Whether there is a pending request for encryption key approval
|
||||||
app_keys: Option<Keys>,
|
pub(crate) pending_request: bool,
|
||||||
/// The key request currently awaiting user approval on this device
|
|
||||||
pending_request: Option<PendingRequest>,
|
|
||||||
/// Handled key-sync request ids, bounded and persisted
|
|
||||||
processed_requests: VecDeque<EventId>,
|
|
||||||
/// Whether an announcement has been made for this device
|
/// Whether an announcement has been made for this device
|
||||||
pub(crate) announcement_existed: Arc<AtomicBool>,
|
pub(crate) announcement_existed: Arc<AtomicBool>,
|
||||||
/// Whether the local key is stale against the current announcement.
|
|
||||||
resync: Arc<AtomicBool>,
|
|
||||||
/// Whether a key rotation is in flight, to coalesce overlapping requests
|
|
||||||
rotating: bool,
|
|
||||||
/// Person directory for requesters shown in notifications
|
/// Person directory for requesters shown in notifications
|
||||||
directory: Entity<Directory>,
|
directory: Entity<Directory>,
|
||||||
/// Relay notification listener
|
/// Relay notification listener
|
||||||
@@ -119,21 +108,6 @@ impl DeviceRegistry {
|
|||||||
if event.signer_changed() && settings.read(cx).is_nip4e_enabled(cx) {
|
if event.signer_changed() && settings.read(cx).is_nip4e_enabled(cx) {
|
||||||
// The old account's state must not leak into the new one
|
// The old account's state must not leak into the new one
|
||||||
this.announcement_existed.store(false, Ordering::Relaxed);
|
this.announcement_existed.store(false, Ordering::Relaxed);
|
||||||
this.resync.store(false, Ordering::Relaxed);
|
|
||||||
// The in-flight request and client key belong to the old account
|
|
||||||
this.app_keys = None;
|
|
||||||
|
|
||||||
if this.pending_request.take().is_some() {
|
|
||||||
// The old approval must not target the new account's signer
|
|
||||||
if let Some(window) = cx.windows().first().copied() {
|
|
||||||
window
|
|
||||||
.update(cx, |_view, window, cx| {
|
|
||||||
window.remove_notification::<DeviceNotification>(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.handle_notifications(cx);
|
this.handle_notifications(cx);
|
||||||
this.get_announcement(cx);
|
this.get_announcement(cx);
|
||||||
}
|
}
|
||||||
@@ -141,19 +115,15 @@ impl DeviceRegistry {
|
|||||||
);
|
);
|
||||||
|
|
||||||
cx.defer(move |cx| {
|
cx.defer(move |cx| {
|
||||||
let _ = entity.update(cx, |this, cx| {
|
entity
|
||||||
this.handle_notifications(cx);
|
.update(cx, |this, cx| this.handle_notifications(cx))
|
||||||
});
|
.ok();
|
||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
signer,
|
signer,
|
||||||
app_keys: None,
|
pending_request: false,
|
||||||
pending_request: None,
|
|
||||||
processed_requests: VecDeque::new(),
|
|
||||||
announcement_existed: Arc::new(AtomicBool::new(false)),
|
announcement_existed: Arc::new(AtomicBool::new(false)),
|
||||||
resync: Arc::new(AtomicBool::new(false)),
|
|
||||||
rotating: false,
|
|
||||||
directory: Directory::new(cx),
|
directory: Directory::new(cx),
|
||||||
notification_listener: None,
|
notification_listener: None,
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
@@ -171,8 +141,6 @@ impl DeviceRegistry {
|
|||||||
let announcement_existed = self.announcement_existed.clone();
|
let announcement_existed = self.announcement_existed.clone();
|
||||||
let (tx, rx) = flume::bounded::<Event>(100);
|
let (tx, rx) = flume::bounded::<Event>(100);
|
||||||
|
|
||||||
let read = credentials::read_processed_requests(cx);
|
|
||||||
|
|
||||||
self.notification_listener = Some(cx.background_spawn(async move {
|
self.notification_listener = Some(cx.background_spawn(async move {
|
||||||
let mut notifications = client.notifications();
|
let mut notifications = client.notifications();
|
||||||
let mut processed_events = HashSet::new();
|
let mut processed_events = HashSet::new();
|
||||||
@@ -207,21 +175,6 @@ impl DeviceRegistry {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
// Hydrate the processed-request log before routing any events
|
|
||||||
match read.await {
|
|
||||||
Ok(bytes) => {
|
|
||||||
let processed = bytes
|
|
||||||
.map(|bytes| parse_processed_requests(&bytes))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
this.update(cx, |this, _cx| {
|
|
||||||
this.processed_requests = processed;
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
Err(e) => log::error!("Failed to read processed key-sync requests: {e}"),
|
|
||||||
}
|
|
||||||
|
|
||||||
while let Ok(event) = rx.recv_async().await {
|
while let Ok(event) = rx.recv_async().await {
|
||||||
match event.kind {
|
match event.kind {
|
||||||
Kind::Custom(10044) => {
|
Kind::Custom(10044) => {
|
||||||
@@ -238,7 +191,7 @@ impl DeviceRegistry {
|
|||||||
// New response event from the master device
|
// New response event from the master device
|
||||||
Kind::Custom(4455) => {
|
Kind::Custom(4455) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.handle_transfer(event, cx);
|
this.extract_encryption(event, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -248,62 +201,12 @@ impl DeviceRegistry {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Record a handled key-sync request id, persisting a bounded log
|
/// Set whether there is a pending request for encryption key approval
|
||||||
fn mark_request_processed(&mut self, event_id: EventId, cx: &mut Context<Self>) {
|
fn set_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
|
||||||
if self.processed_requests.contains(&event_id) {
|
self.pending_request = pending;
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.processed_requests.push_back(event_id);
|
|
||||||
while self.processed_requests.len() > PROCESSED_REQUESTS_LIMIT {
|
|
||||||
self.processed_requests.pop_front();
|
|
||||||
}
|
|
||||||
|
|
||||||
let bytes: Vec<u8> = self
|
|
||||||
.processed_requests
|
|
||||||
.iter()
|
|
||||||
.flat_map(|id| id.to_hex().into_bytes())
|
|
||||||
.collect();
|
|
||||||
let write = credentials::write_processed_requests(cx, &bytes);
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
if let Err(e) = write.await {
|
|
||||||
log::error!("Failed to persist processed key-sync requests: {e}");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Withdraw the pending approval.
|
|
||||||
fn resolve_pending_request(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let Some(pending) = self.pending_request.take() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
self.mark_request_processed(pending.event.id, cx);
|
|
||||||
|
|
||||||
if let Some(window) = cx.windows().first().copied() {
|
|
||||||
window
|
|
||||||
.update(cx, |_view, window, cx| {
|
|
||||||
window.remove_notification::<DeviceNotification>(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Route a key transfer.
|
|
||||||
fn handle_transfer(&mut self, event: Event, cx: &mut Context<Self>) {
|
|
||||||
let resolved = self
|
|
||||||
.pending_request
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|pending| transfer_addresses(&event, pending.client_key));
|
|
||||||
|
|
||||||
if resolved {
|
|
||||||
self.resolve_pending_request(cx);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.extract_encryption(event, cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the signer
|
/// Get the signer
|
||||||
pub fn signer(&self, cx: &App) -> Option<UniversalSigner> {
|
pub fn signer(&self, cx: &App) -> Option<UniversalSigner> {
|
||||||
self.signer.read(cx).clone()
|
self.signer.read(cx).clone()
|
||||||
@@ -315,16 +218,9 @@ impl DeviceRegistry {
|
|||||||
*this = Some(UniversalSigner::new(new_signer));
|
*this = Some(UniversalSigner::new(new_signer));
|
||||||
cx.notify();
|
cx.notify();
|
||||||
});
|
});
|
||||||
// The local key is now consistent with the announcement
|
|
||||||
self.resync.store(false, Ordering::Release);
|
|
||||||
cx.emit(DeviceEvent::Set);
|
cx.emit(DeviceEvent::Set);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the local encryption key is stale against the current announcement.
|
|
||||||
pub fn is_resyncing(&self) -> bool {
|
|
||||||
self.resync.load(Ordering::Acquire)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Backup the encryption's secret key, returning the `nsec1...` content
|
/// Backup the encryption's secret key, returning the `nsec1...` content
|
||||||
pub fn backup_bytes(&self, cx: &App) -> Task<Result<String, Error>> {
|
pub fn backup_bytes(&self, cx: &App) -> Task<Result<String, Error>> {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
@@ -427,88 +323,6 @@ impl DeviceRegistry {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace the encryption key with a new one, archiving the old key.
|
|
||||||
pub fn rotate(&mut self, cx: &mut Context<Self>) {
|
|
||||||
if self.rotating {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.rotating = true;
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let client = nostr.read(cx).client();
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let result: Result<Keys, Error> = async {
|
|
||||||
// Archive the current key before replacing it
|
|
||||||
if let Ok(old) = get_keys(&client, &signer).await {
|
|
||||||
archive_key(&client, &signer, &old.secret_key().to_secret_hex()).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let created = this
|
|
||||||
.update(cx, |this, cx| this.create_encryption(Keys::generate(), cx))?
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_signer(created.clone(), cx);
|
|
||||||
this.wait_for_request(cx);
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(created)
|
|
||||||
}
|
|
||||||
.await;
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.rotating = false;
|
|
||||||
if let Err(e) = result {
|
|
||||||
cx.emit(DeviceEvent::error(e.to_string()));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rotate the encryption key when the configured interval has elapsed.
|
|
||||||
///
|
|
||||||
/// Runs after the announcement reconciled, outside the blocking boot path.
|
|
||||||
pub fn rotate_if_due(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let Some(interval_days) = AppSettings::get_nip4e_rotation_days(cx) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let interval_days = interval_days.clamp(NIP4E_ROTATION_MIN_DAYS, NIP4E_ROTATION_MAX_DAYS);
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let client = nostr.read(cx).client();
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let Ok(keys) = load_device_keys(&client, &signer).await else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
|
|
||||||
let elapsed = Timestamp::now()
|
|
||||||
.as_secs()
|
|
||||||
.saturating_sub(keys.created_at.as_secs());
|
|
||||||
if elapsed < u64::from(interval_days) * SECONDS_PER_DAY {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| this.rotate(cx)).ok();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Load encryption keys retired by a rotation from the local database.
|
|
||||||
pub async fn archived_keys<S>(client: &Client, signer: &S) -> Result<Vec<Keys>, Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
storage::archived_keys(client, signer).await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create new encryption key and announce it to user's relay list
|
/// Create new encryption key and announce it to user's relay list
|
||||||
fn create_encryption(&self, keys: Keys, cx: &App) -> Task<Result<Keys, Error>> {
|
fn create_encryption(&self, keys: Keys, cx: &App) -> Task<Result<Keys, Error>> {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
@@ -517,7 +331,6 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
let secret = keys.secret_key().to_secret_hex();
|
let secret = keys.secret_key().to_secret_hex();
|
||||||
let n = keys.public_key();
|
let n = keys.public_key();
|
||||||
let created_at = Timestamp::now();
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Construct an announcement event
|
// Construct an announcement event
|
||||||
@@ -527,7 +340,7 @@ impl DeviceRegistry {
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Persist the key locally before announcing it
|
// Persist the key locally before announcing it
|
||||||
set_keys(&client, &signer, &secret, created_at).await?;
|
set_keys(&client, &signer, &secret).await?;
|
||||||
|
|
||||||
// Publish announcement
|
// Publish announcement
|
||||||
client
|
client
|
||||||
@@ -570,12 +383,10 @@ impl DeviceRegistry {
|
|||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
this.wait_for_request(cx);
|
this.wait_for_request(cx);
|
||||||
this.rotate_if_due(cx);
|
|
||||||
})?;
|
})?;
|
||||||
} else {
|
} else {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.resync.store(true, Ordering::Release);
|
this.request(cx);
|
||||||
this.request(Some(device_pubkey), cx);
|
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -603,17 +414,15 @@ impl DeviceRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Request encryption keys from other device
|
/// Request encryption keys from other device
|
||||||
pub(crate) fn request(
|
pub(crate) fn request(&mut self, cx: &mut Context<Self>) {
|
||||||
&mut self,
|
|
||||||
expected_encryption: Option<PublicKey>,
|
|
||||||
cx: &mut Context<Self>,
|
|
||||||
) {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
let app_keys = self.app_keys.get_or_insert_with(Keys::generate).clone();
|
|
||||||
|
let app_keys_task = get_or_init_app_keys(cx);
|
||||||
|
|
||||||
let task: Task<Result<Option<Event>, Error>> = cx.background_spawn(async move {
|
let task: Task<Result<Option<Event>, Error>> = cx.background_spawn(async move {
|
||||||
|
let app_keys = app_keys_task.await?;
|
||||||
let app_pubkey = app_keys.public_key();
|
let app_pubkey = app_keys.public_key();
|
||||||
let public_key = signer.get_public_key_async().await?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
|
|
||||||
@@ -625,7 +434,8 @@ impl DeviceRegistry {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if let Some(event) = client.database().query(filter).await?.into_iter().next() {
|
if let Some(event) = client.database().query(filter).await?.into_iter().next() {
|
||||||
// Only reuse the stored approval if its key is still valid
|
// Only reuse the stored approval if its key is still valid,
|
||||||
|
// otherwise it's stale and a fresh request is needed
|
||||||
if decrypt_approval(&client, &app_keys, public_key, &event)
|
if decrypt_approval(&client, &app_keys, public_key, &event)
|
||||||
.await
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
@@ -634,26 +444,9 @@ impl DeviceRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// No usable approval event found, construct a request event.
|
// No usable approval event found, construct a request event
|
||||||
//
|
|
||||||
// The `pubkey` tag is a compatibility alias for the draft's `P`,
|
|
||||||
// `relay` hints tell other devices where the response is accepted,
|
|
||||||
// `n` names the exact key this device expects to be transferred
|
|
||||||
let mut tags = vec![
|
|
||||||
Tag::custom("P", vec![app_pubkey]),
|
|
||||||
Tag::custom("pubkey", vec![app_pubkey]),
|
|
||||||
];
|
|
||||||
|
|
||||||
for url in write_relay_hints(&client, public_key).await? {
|
|
||||||
tags.push(Tag::custom("relay", vec![url.to_string()]));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(expected) = expected_encryption {
|
|
||||||
tags.push(Tag::custom("n", vec![expected]));
|
|
||||||
}
|
|
||||||
|
|
||||||
let event = EventBuilder::new(Kind::Custom(4454), "")
|
let event = EventBuilder::new(Kind::Custom(4454), "")
|
||||||
.tags(tags)
|
.tags(vec![Tag::custom("P", vec![app_pubkey])])
|
||||||
.finalize_async(&signer)
|
.finalize_async(&signer)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -690,13 +483,19 @@ impl DeviceRegistry {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
|
let app_keys_task = get_or_init_app_keys(cx);
|
||||||
let Some(app_keys) = self.app_keys.clone() else {
|
|
||||||
log::warn!("Cannot wait for approval without a client key");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
|
let app_keys = match app_keys_task.await {
|
||||||
|
Ok(app_keys) => app_keys,
|
||||||
|
Err(e) => {
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
|
})?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(DeviceEvent::Requesting(authorization_code(
|
cx.emit(DeviceEvent::Requesting(authorization_code(
|
||||||
&app_keys.public_key(),
|
&app_keys.public_key(),
|
||||||
@@ -706,7 +505,7 @@ impl DeviceRegistry {
|
|||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key_async().await?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
|
|
||||||
// Only approvals addressed to this device's client key matter
|
// Only approvals addressed to this device's app key matter
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::Custom(4455))
|
.kind(Kind::Custom(4455))
|
||||||
.author(public_key)
|
.author(public_key)
|
||||||
@@ -730,18 +529,15 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
/// Parse the approval event to get encryption key then set it
|
/// Parse the approval event to get encryption key then set it
|
||||||
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
|
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||||
|
let app_keys_task = get_or_init_app_keys(cx);
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
let Some(app_keys) = self.app_keys.clone() else {
|
|
||||||
log::warn!("Ignoring key transfer addressed to another device");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let approval_id = event.id;
|
let approval_id = event.id;
|
||||||
|
|
||||||
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||||
|
let app_keys = app_keys_task.await?;
|
||||||
let identity = signer.get_public_key_async().await?;
|
let identity = signer.get_public_key_async().await?;
|
||||||
let keys = decrypt_approval(&client, &app_keys, identity, &event).await?;
|
let keys = decrypt_approval(&client, &app_keys, identity, &event).await?;
|
||||||
|
|
||||||
@@ -753,14 +549,14 @@ impl DeviceRegistry {
|
|||||||
Ok(keys) => {
|
Ok(keys) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
// The client key was consumed; start fresh on the next request
|
|
||||||
this.app_keys = None;
|
|
||||||
// Clean up our request and the approval event from relays
|
// Clean up our request and the approval event from relays
|
||||||
this.cleanup_sync_events(approval_id, cx);
|
this.cleanup_sync_events(approval_id, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::warn!("Ignoring key transfer: {e}");
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -814,58 +610,40 @@ impl DeviceRegistry {
|
|||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
|
// Get user's write relays
|
||||||
let event = event.clone();
|
let event = event.clone();
|
||||||
let request_id = event.id;
|
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
// Get device keys
|
// Get device keys
|
||||||
let keys = get_keys(&client, &signer).await?;
|
let keys = get_keys(&client, &signer).await?;
|
||||||
let secret = keys.secret_key().to_secret_hex();
|
let secret = keys.secret_key().to_secret_hex();
|
||||||
let identity = signer.get_public_key_async().await?;
|
|
||||||
|
|
||||||
// Extract the target public key from the event tags
|
// Extract the target public key from the event tags
|
||||||
let target =
|
let target = event
|
||||||
client_pubkey_from_event(&event).context("Target is not a valid public key")?;
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "P")
|
||||||
|
.and_then(|tag| tag.content())
|
||||||
|
.and_then(|content| PublicKey::parse(content).ok())
|
||||||
|
.context("Target is not a valid public key")?;
|
||||||
|
|
||||||
// The requester may pin the exact key it expects
|
// Encrypt the device keys with the user's signer
|
||||||
if let Some(requested) = requested_encryption_key(&event)
|
let payload = keys.nip44_encrypt_async(&target, &secret).await?;
|
||||||
&& requested != keys.public_key()
|
|
||||||
{
|
|
||||||
return Err(anyhow!(
|
|
||||||
"The requesting device expects an encryption key this device no longer holds"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encrypt to a fresh one-time keypair so the transfer event
|
|
||||||
// can never be decrypted with the long-lived encryption key.
|
|
||||||
let sender = Keys::generate();
|
|
||||||
let payload = sender.nip44_encrypt_async(&target, &secret).await?;
|
|
||||||
|
|
||||||
// Construct the response event
|
// Construct the response event
|
||||||
//
|
//
|
||||||
// P tag: the one-time sender key used for the encryption
|
// P tag: the current device's public key
|
||||||
// p tag: the account identity, for inbox routing
|
// p tag: the requester's public key
|
||||||
// p tag: the requester's client key
|
let event = EventBuilder::new(Kind::Custom(4455), payload)
|
||||||
let response = EventBuilder::new(Kind::Custom(4455), payload)
|
|
||||||
.tags(vec![
|
.tags(vec![
|
||||||
Tag::custom("P", vec![sender.public_key().to_hex()]),
|
Tag::custom("P", vec![keys.public_key().to_hex()]),
|
||||||
Tag::public_key(identity),
|
|
||||||
Tag::public_key(target),
|
Tag::public_key(target),
|
||||||
])
|
])
|
||||||
.finalize_async(&signer)
|
.finalize_async(&signer)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let relays = merge_relays(
|
// Send the response event to the user's relay list
|
||||||
write_relay_hints(&client, identity).await?,
|
client.send_event(&event).to_nip65().await?;
|
||||||
request_relay_hints(&event),
|
|
||||||
);
|
|
||||||
|
|
||||||
let send = client.send_event(&response);
|
|
||||||
if relays.is_empty() {
|
|
||||||
send.to_nip65().await?;
|
|
||||||
} else {
|
|
||||||
send.to(relays).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
@@ -874,11 +652,8 @@ impl DeviceRegistry {
|
|||||||
match task.await {
|
match task.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
// Record the request as handled so it cannot resurface
|
|
||||||
this.mark_request_processed(request_id, cx);
|
|
||||||
// Allow future requests to surface again
|
// Allow future requests to surface again
|
||||||
this.pending_request = None;
|
this.set_pending_request(false, cx);
|
||||||
cx.notify();
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
cx.update(|window, cx| {
|
cx.update(|window, cx| {
|
||||||
@@ -903,70 +678,21 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
/// Handle encryption request
|
/// Handle encryption request
|
||||||
fn ask_for_approval(&mut self, event: Event, cx: &mut Context<Self>) {
|
fn ask_for_approval(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||||
let Some(client_key) = client_pubkey_from_event(&event) else {
|
// Ignore if there is already a pending request
|
||||||
log::warn!("Ignoring invalid encryption key request: no valid requester key");
|
if self.pending_request {
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let read = credentials::read_processed_requests(cx);
|
|
||||||
cx.spawn(async move |this, cx| {
|
|
||||||
let processed = match read.await {
|
|
||||||
Ok(bytes) => bytes
|
|
||||||
.map(|bytes| parse_processed_requests(&bytes).contains(&event.id))
|
|
||||||
.unwrap_or(false),
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to read processed key-sync requests: {e}");
|
|
||||||
false
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
if processed || this.processed_requests.contains(&event.id) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
self.set_pending_request(true, cx);
|
||||||
|
|
||||||
match this.pending_request.take() {
|
let notification = match self.notification(event, cx) {
|
||||||
// A retry signs a new request id but keeps the same client key
|
|
||||||
Some(mut pending) if pending.client_key == client_key => {
|
|
||||||
this.mark_request_processed(event.id, cx);
|
|
||||||
pending.event = event;
|
|
||||||
this.pending_request = Some(pending);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A different client key is a remounted requester
|
|
||||||
other => {
|
|
||||||
if let Some(pending) = other {
|
|
||||||
this.mark_request_processed(pending.event.id, cx);
|
|
||||||
if let Some(window) = cx.windows().first().copied() {
|
|
||||||
window
|
|
||||||
.update(cx, |_view, window, cx| {
|
|
||||||
window.remove_notification::<DeviceNotification>(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.show_approval(event, client_key, cx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build and surface the approval notification for a key request
|
|
||||||
fn show_approval(&mut self, event: Event, client_key: PublicKey, cx: &mut Context<Self>) {
|
|
||||||
let notification = match self.notification(event.clone(), cx) {
|
|
||||||
Ok(notification) => notification,
|
Ok(notification) => notification,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::warn!("Ignoring invalid encryption key request: {e}");
|
log::warn!("Ignoring invalid encryption key request: {e}");
|
||||||
|
self.set_pending_request(false, cx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.pending_request = Some(PendingRequest { event, client_key });
|
|
||||||
cx.notify();
|
|
||||||
|
|
||||||
if let Some(window) = cx.windows().first().copied() {
|
if let Some(window) = cx.windows().first().copied() {
|
||||||
if let Err(error) = window.update(cx, |_view, window, cx| {
|
if let Err(error) = window.update(cx, |_view, window, cx| {
|
||||||
window.push_notification(notification, cx);
|
window.push_notification(notification, cx);
|
||||||
@@ -989,16 +715,18 @@ impl DeviceRegistry {
|
|||||||
compare the code with the one shown on the requesting \
|
compare the code with the one shown on the requesting \
|
||||||
device.";
|
device.";
|
||||||
|
|
||||||
let requester =
|
let requester = event
|
||||||
client_pubkey_from_event(&event).context("Request has no valid requester key")?;
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "P")
|
||||||
|
.and_then(|tag| tag.content())
|
||||||
|
.and_then(|content| PublicKey::parse(content).ok())
|
||||||
|
.context("Request has no valid requester key")?;
|
||||||
|
|
||||||
let code = authorization_code(&requester);
|
let code = authorization_code(&requester);
|
||||||
let code_label = code.clone();
|
|
||||||
|
|
||||||
let directory = self.directory.clone();
|
let directory = self.directory.clone();
|
||||||
directory.update(cx, |directory, cx| {
|
directory.update(cx, |directory, cx| directory.track([requester], cx));
|
||||||
directory.track([requester], cx);
|
let code_label = code.clone();
|
||||||
});
|
|
||||||
|
|
||||||
let entity = cx.entity().downgrade();
|
let entity = cx.entity().downgrade();
|
||||||
let loading = Rc::new(Cell::new(false));
|
let loading = Rc::new(Cell::new(false));
|
||||||
@@ -1103,111 +831,6 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
struct DeviceNotification;
|
struct DeviceNotification;
|
||||||
|
|
||||||
/// A key request awaiting user approval on this device
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct PendingRequest {
|
|
||||||
event: Event,
|
|
||||||
client_key: PublicKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep the durable processed-request log bounded
|
|
||||||
const PROCESSED_REQUESTS_LIMIT: usize = 256;
|
|
||||||
|
|
||||||
/// Parse concatenated hex event ids
|
|
||||||
fn parse_processed_requests(bytes: &[u8]) -> VecDeque<EventId> {
|
|
||||||
let Ok(hex) = std::str::from_utf8(bytes) else {
|
|
||||||
return VecDeque::new();
|
|
||||||
};
|
|
||||||
|
|
||||||
hex.as_bytes()
|
|
||||||
.as_chunks::<64>()
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.filter_map(|chunk| EventId::from_hex(std::str::from_utf8(chunk).ok()?).ok())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract the client public key from an event.
|
|
||||||
fn client_pubkey_from_event(event: &Event) -> Option<PublicKey> {
|
|
||||||
let key = event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|tag| tag.kind() == "P")
|
|
||||||
.and_then(|tag| tag.content())
|
|
||||||
.and_then(|content| PublicKey::parse(content).ok());
|
|
||||||
|
|
||||||
key.or_else(|| {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|tag| tag.kind() == "pubkey")
|
|
||||||
.and_then(|tag| tag.content())
|
|
||||||
.and_then(|content| PublicKey::parse(content).ok())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the transfer event is p-tagged to the given client key
|
|
||||||
fn transfer_addresses(event: &Event, client_key: PublicKey) -> bool {
|
|
||||||
event.tags.iter().any(|tag| {
|
|
||||||
tag.kind() == "p"
|
|
||||||
&& tag
|
|
||||||
.content()
|
|
||||||
.and_then(|content| PublicKey::parse(content).ok())
|
|
||||||
.is_some_and(|key| key == client_key)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the `relay` hints attached to a key request.
|
|
||||||
fn request_relay_hints(event: &Event) -> Vec<RelayUrl> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.filter(|tag| tag.kind() == "relay")
|
|
||||||
.filter_map(|tag| {
|
|
||||||
tag.content()
|
|
||||||
.and_then(|content| RelayUrl::parse(content).ok())
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the optional `n` tag of a key request.
|
|
||||||
fn requested_encryption_key(event: &Event) -> Option<PublicKey> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|tag| tag.kind() == "n")
|
|
||||||
.and_then(|tag| tag.content())
|
|
||||||
.and_then(|content| PublicKey::parse(content).ok())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Collect the user's NIP-65 write relays.
|
|
||||||
async fn write_relay_hints(client: &Client, identity: PublicKey) -> Result<Vec<RelayUrl>, Error> {
|
|
||||||
let filter = Filter::new()
|
|
||||||
.kind(Kind::RelayList)
|
|
||||||
.author(identity)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
let Some(event) = client.database().query(filter).await?.into_iter().next() else {
|
|
||||||
return Ok(vec![]);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Unmarked relays serve both reads and writes
|
|
||||||
Ok(nip65::extract_relay_list(&event)
|
|
||||||
.filter(|(_, metadata)| *metadata != Some(RelayMetadata::Read))
|
|
||||||
.map(|(url, _)| url)
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Merge relay lists, dropping duplicates
|
|
||||||
fn merge_relays(first: Vec<RelayUrl>, second: Vec<RelayUrl>) -> Vec<RelayUrl> {
|
|
||||||
first
|
|
||||||
.into_iter()
|
|
||||||
.chain(second)
|
|
||||||
.collect::<HashSet<_>>()
|
|
||||||
.into_iter()
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first eight hexadecimal characters of the client public key.
|
/// The first eight hexadecimal characters of the client public key.
|
||||||
fn authorization_code(public_key: &PublicKey) -> SharedString {
|
fn authorization_code(public_key: &PublicKey) -> SharedString {
|
||||||
let hex = public_key.to_hex();
|
let hex = public_key.to_hex();
|
||||||
@@ -1215,6 +838,35 @@ fn authorization_code(public_key: &PublicKey) -> SharedString {
|
|||||||
SharedString::from(format!("{} {}", &code[..4], &code[4..]))
|
SharedString::from(format!("{} {}", &code[..4], &code[4..]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get or create new app keys (async, returns a task)
|
||||||
|
fn get_or_init_app_keys(cx: &App) -> Task<Result<Keys, Error>> {
|
||||||
|
let read = credentials::read_app_keys(cx);
|
||||||
|
|
||||||
|
cx.spawn(async move |cx| {
|
||||||
|
if let Ok(Some(secret)) = read.await
|
||||||
|
&& let Ok(keys) = SecretKey::from_slice(&secret).map(Keys::new)
|
||||||
|
{
|
||||||
|
return Ok(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
// No stored keys found or invalid — generate new ones
|
||||||
|
let keys = Keys::generate();
|
||||||
|
let secret = keys.secret_key().to_secret_bytes();
|
||||||
|
|
||||||
|
cx.update(|cx| {
|
||||||
|
let write = credentials::write_app_keys(cx, &secret);
|
||||||
|
cx.background_spawn(async move {
|
||||||
|
if let Err(e) = write.await {
|
||||||
|
log::error!("Failed to persist app keys: {e}")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(keys)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Decrypt and validate an approval event against the current announcement.
|
/// Decrypt and validate an approval event against the current announcement.
|
||||||
async fn decrypt_approval(
|
async fn decrypt_approval(
|
||||||
client: &Client,
|
client: &Client,
|
||||||
@@ -1222,7 +874,13 @@ async fn decrypt_approval(
|
|||||||
identity: PublicKey,
|
identity: PublicKey,
|
||||||
event: &Event,
|
event: &Event,
|
||||||
) -> Result<Keys, Error> {
|
) -> Result<Keys, Error> {
|
||||||
let master = client_pubkey_from_event(event).context("Invalid event's tags")?;
|
let master = event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "P")
|
||||||
|
.and_then(|tag| tag.content())
|
||||||
|
.and_then(|content| PublicKey::parse(content).ok())
|
||||||
|
.context("Invalid event's tags")?;
|
||||||
|
|
||||||
let decrypted = app_keys
|
let decrypted = app_keys
|
||||||
.nip44_decrypt_async(&master, event.content.as_str())
|
.nip44_decrypt_async(&master, event.content.as_str())
|
||||||
@@ -1231,41 +889,13 @@ async fn decrypt_approval(
|
|||||||
let secret = SecretKey::from_hex(&decrypted)?;
|
let secret = SecretKey::from_hex(&decrypted)?;
|
||||||
let keys = Keys::new(secret);
|
let keys = Keys::new(secret);
|
||||||
|
|
||||||
// Reject approvals carrying a key that no longer matches the published announcement
|
// Reject approvals carrying a key that no longer matches the published announcement.
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::Custom(10044))
|
.kind(Kind::Custom(10044))
|
||||||
.author(identity)
|
.author(identity)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
let announcement = client
|
if let Some(announcement) = client.database().query(filter).await?.into_iter().next() {
|
||||||
.database()
|
|
||||||
.query(filter.clone())
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.next();
|
|
||||||
|
|
||||||
let announcement = match announcement {
|
|
||||||
Some(announcement) => Some(announcement),
|
|
||||||
None => {
|
|
||||||
let mut stream = client
|
|
||||||
.stream_events(filter)
|
|
||||||
.timeout(Duration::from_secs(3))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
stream
|
|
||||||
.next()
|
|
||||||
.await
|
|
||||||
.map(|(_url, result)| result)
|
|
||||||
.transpose()?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(announcement) = announcement else {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"No encryption announcement available to validate the approval"
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
let announced = announcement
|
let announced = announcement
|
||||||
.tags
|
.tags
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1277,6 +907,53 @@ async fn decrypt_approval(
|
|||||||
if keys.public_key() != announced {
|
if keys.public_key() != announced {
|
||||||
return Err(anyhow!("Approval key doesn't match the announcement"));
|
return Err(anyhow!("Approval key doesn't match the announcement"));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(keys)
|
Ok(keys)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Encrypt and store device keys in the local database.
|
||||||
|
async fn set_keys<S>(client: &Client, signer: &S, secret: &str) -> Result<(), Error>
|
||||||
|
where
|
||||||
|
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||||
|
{
|
||||||
|
let public_key = signer.get_public_key_async().await?;
|
||||||
|
let content = signer.nip44_encrypt_async(&public_key, secret).await?;
|
||||||
|
|
||||||
|
// Construct the application data event
|
||||||
|
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
||||||
|
.tag(Tag::identifier(IDENTIFIER))
|
||||||
|
.finalize_async(signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Save the event to the database
|
||||||
|
client.database().save_event(&event).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get device keys from the local database.
|
||||||
|
async fn get_keys<S>(client: &Client, signer: &S) -> Result<Keys, Error>
|
||||||
|
where
|
||||||
|
S: AsyncGetPublicKey + AsyncNip44 + ?Sized,
|
||||||
|
{
|
||||||
|
let public_key = signer.get_public_key_async().await?;
|
||||||
|
|
||||||
|
let filter = Filter::new()
|
||||||
|
.kind(Kind::ApplicationSpecificData)
|
||||||
|
.identifier(IDENTIFIER)
|
||||||
|
.author(public_key);
|
||||||
|
|
||||||
|
if let Some(event) = client.database().query(filter).await?.first() {
|
||||||
|
let content = signer
|
||||||
|
.nip44_decrypt_async(&public_key, &event.content)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let secret = SecretKey::parse(&content)?;
|
||||||
|
let keys = Keys::new(secret);
|
||||||
|
|
||||||
|
Ok(keys)
|
||||||
|
} else {
|
||||||
|
Err(anyhow!("Key not found"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,174 +0,0 @@
|
|||||||
use anyhow::{Error, anyhow};
|
|
||||||
use nostr_sdk::prelude::*;
|
|
||||||
|
|
||||||
/// The storage identifier for the device encryption key
|
|
||||||
const IDENTIFIER: &str = "coop:device";
|
|
||||||
/// The storage identifier for encryption keys retired by a rotation
|
|
||||||
const ARCHIVE_IDENTIFIER: &str = "coop:device-archive";
|
|
||||||
/// Keep the archived key list bounded
|
|
||||||
const ARCHIVE_LIMIT: usize = 10;
|
|
||||||
/// Seconds in a day, for rotation intervals
|
|
||||||
pub(crate) const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
|
|
||||||
|
|
||||||
/// Device encryption key material with its creation time
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub(crate) struct DeviceKeys {
|
|
||||||
pub(crate) keys: Keys,
|
|
||||||
pub(crate) created_at: Timestamp,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encode the stored key content: secret hex and creation time
|
|
||||||
fn encode_keys_content(secret: &str, created_at: &Timestamp) -> String {
|
|
||||||
format!("{secret}\n{}", created_at.as_secs())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse stored key content.
|
|
||||||
fn parse_keys_content(content: &str) -> Result<(SecretKey, Timestamp), Error> {
|
|
||||||
match content.split_once('\n') {
|
|
||||||
Some((secret, created_at)) => {
|
|
||||||
let created_at = created_at
|
|
||||||
.trim()
|
|
||||||
.parse::<u64>()
|
|
||||||
.unwrap_or_else(|_| Timestamp::now().as_secs());
|
|
||||||
Ok((
|
|
||||||
SecretKey::from_hex(secret)?,
|
|
||||||
Timestamp::from_secs(created_at),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
None => Ok((SecretKey::from_hex(content)?, Timestamp::now())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse archived secrets from stored content, one hex secret per line
|
|
||||||
fn parse_archived_keys(content: &str) -> Vec<Keys> {
|
|
||||||
content
|
|
||||||
.lines()
|
|
||||||
.filter_map(|line| SecretKey::from_hex(line.trim()).ok())
|
|
||||||
.map(Keys::new)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Load the device keys with their creation time from the local database.
|
|
||||||
pub(crate) async fn load_device_keys<S>(client: &Client, signer: &S) -> Result<DeviceKeys, Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
let public_key = signer.get_public_key_async().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new()
|
|
||||||
.kind(Kind::ApplicationSpecificData)
|
|
||||||
.identifier(IDENTIFIER)
|
|
||||||
.author(public_key);
|
|
||||||
|
|
||||||
let Some(event) = client.database().query(filter).await?.into_iter().next() else {
|
|
||||||
return Err(anyhow!("Key not found"));
|
|
||||||
};
|
|
||||||
|
|
||||||
let content = signer
|
|
||||||
.nip44_decrypt_async(&public_key, &event.content)
|
|
||||||
.await?;
|
|
||||||
let (secret, created_at) = parse_keys_content(&content)?;
|
|
||||||
|
|
||||||
Ok(DeviceKeys {
|
|
||||||
keys: Keys::new(secret),
|
|
||||||
created_at,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encrypt and store device keys in the local database.
|
|
||||||
pub(crate) async fn set_keys<S>(
|
|
||||||
client: &Client,
|
|
||||||
signer: &S,
|
|
||||||
secret: &str,
|
|
||||||
created_at: Timestamp,
|
|
||||||
) -> Result<(), Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
let public_key = signer.get_public_key_async().await?;
|
|
||||||
let content = signer
|
|
||||||
.nip44_encrypt_async(&public_key, &encode_keys_content(secret, &created_at))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Construct the application data event
|
|
||||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
|
||||||
.tag(Tag::identifier(IDENTIFIER))
|
|
||||||
.finalize_async(signer)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Save the event to the database
|
|
||||||
client.database().save_event(&event).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append an encryption secret to the bounded archive of retired keys.
|
|
||||||
pub(crate) async fn archive_key<S>(client: &Client, signer: &S, secret: &str) -> Result<(), Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
let public_key = signer.get_public_key_async().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new()
|
|
||||||
.kind(Kind::ApplicationSpecificData)
|
|
||||||
.identifier(ARCHIVE_IDENTIFIER)
|
|
||||||
.author(public_key);
|
|
||||||
|
|
||||||
let mut archived: Vec<String> = match client.database().query(filter).await?.into_iter().next()
|
|
||||||
{
|
|
||||||
Some(event) => {
|
|
||||||
let content = signer
|
|
||||||
.nip44_decrypt_async(&public_key, &event.content)
|
|
||||||
.await?;
|
|
||||||
content.lines().map(str::to_string).collect()
|
|
||||||
}
|
|
||||||
None => vec![],
|
|
||||||
};
|
|
||||||
|
|
||||||
archived.insert(0, secret.to_string());
|
|
||||||
archived.truncate(ARCHIVE_LIMIT);
|
|
||||||
|
|
||||||
let content = signer
|
|
||||||
.nip44_encrypt_async(&public_key, &archived.join("\n"))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
|
||||||
.tag(Tag::identifier(ARCHIVE_IDENTIFIER))
|
|
||||||
.finalize_async(signer)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
client.database().save_event(&event).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get device keys from the local database.
|
|
||||||
pub(crate) async fn get_keys<S>(client: &Client, signer: &S) -> Result<Keys, Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
Ok(load_device_keys(client, signer).await?.keys)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Load encryption keys retired by a rotation from the local database.
|
|
||||||
pub(crate) async fn archived_keys<S>(client: &Client, signer: &S) -> Result<Vec<Keys>, Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncNip44 + ?Sized,
|
|
||||||
{
|
|
||||||
let public_key = signer.get_public_key_async().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new()
|
|
||||||
.kind(Kind::ApplicationSpecificData)
|
|
||||||
.identifier(ARCHIVE_IDENTIFIER)
|
|
||||||
.author(public_key);
|
|
||||||
|
|
||||||
let Some(event) = client.database().query(filter).await?.into_iter().next() else {
|
|
||||||
return Ok(vec![]);
|
|
||||||
};
|
|
||||||
|
|
||||||
let content = signer
|
|
||||||
.nip44_decrypt_async(&public_key, &event.content)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(parse_archived_keys(&content))
|
|
||||||
}
|
|
||||||
@@ -54,7 +54,7 @@ impl EventEmitter<PersonEvent> for PersonRegistry {}
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
enum Dispatch {
|
enum Dispatch {
|
||||||
Person(Box<Person>),
|
Person(Person),
|
||||||
Announcement(Event),
|
Announcement(Event),
|
||||||
Relays(Event),
|
Relays(Event),
|
||||||
Emojis(Event),
|
Emojis(Event),
|
||||||
@@ -111,7 +111,7 @@ impl PersonRegistry {
|
|||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
match event {
|
match event {
|
||||||
Dispatch::Person(person) => {
|
Dispatch::Person(person) => {
|
||||||
this.insert(*person, cx);
|
this.insert(person, cx);
|
||||||
}
|
}
|
||||||
Dispatch::Announcement(event) => {
|
Dispatch::Announcement(event) => {
|
||||||
this.set_announcement(&event, cx);
|
this.set_announcement(&event, cx);
|
||||||
@@ -175,11 +175,7 @@ impl PersonRegistry {
|
|||||||
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
|
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
|
||||||
let person = Person::new(event.pubkey, metadata);
|
let person = Person::new(event.pubkey, metadata);
|
||||||
|
|
||||||
if tx
|
if tx.send_async(Dispatch::Person(person)).await.is_err() {
|
||||||
.send_async(Dispatch::Person(Box::new(person)))
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
log::warn!("Channel closed, dropping metadata event");
|
log::warn!("Channel closed, dropping metadata event");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,13 +144,6 @@ impl Person {
|
|||||||
|
|
||||||
/// Set profile encryption keys announcement
|
/// Set profile encryption keys announcement
|
||||||
pub(crate) fn set_announcement(&mut self, announcement: Announcement) {
|
pub(crate) fn set_announcement(&mut self, announcement: Announcement) {
|
||||||
// A delayed or repeated announcement must not roll the key back
|
|
||||||
if let Some(current) = &self.announcement
|
|
||||||
&& !announcement.is_newer_than(current)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.announcement = Some(announcement);
|
self.announcement = Some(announcement);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-39
@@ -100,12 +100,7 @@ pub fn persisted_theme() -> ThemeSettings {
|
|||||||
|
|
||||||
const DEFAULT_FILE_SERVER: &str = "https://nostr.download/";
|
const DEFAULT_FILE_SERVER: &str = "https://nostr.download/";
|
||||||
const LEGACY_FILE_SERVER: &str = "blossom.band";
|
const LEGACY_FILE_SERVER: &str = "blossom.band";
|
||||||
/// Minimum days between automatic encryption key rotations
|
|
||||||
pub const NIP4E_ROTATION_MIN_DAYS: u32 = 1;
|
|
||||||
/// Maximum days between automatic encryption key rotations
|
|
||||||
pub const NIP4E_ROTATION_MAX_DAYS: u32 = 90;
|
|
||||||
/// Days between automatic encryption key rotations when enabled
|
|
||||||
pub const NIP4E_ROTATION_DEFAULT_DAYS: u32 = 30;
|
|
||||||
/// Built-in image shown behind chat and group panels
|
/// Built-in image shown behind chat and group panels
|
||||||
pub const DEFAULT_BACKGROUND: &str = "brand/default-bg.jpg";
|
pub const DEFAULT_BACKGROUND: &str = "brand/default-bg.jpg";
|
||||||
|
|
||||||
@@ -152,7 +147,6 @@ setting_accessors! {
|
|||||||
pub screening: bool,
|
pub screening: bool,
|
||||||
pub wot_auto_trust: bool,
|
pub wot_auto_trust: bool,
|
||||||
pub nip4e: bool,
|
pub nip4e: bool,
|
||||||
pub nip4e_rotation_days: Option<u32>,
|
|
||||||
pub hide_group_notice: bool,
|
pub hide_group_notice: bool,
|
||||||
pub file_server: Url,
|
pub file_server: Url,
|
||||||
pub panel_background: bool,
|
pub panel_background: bool,
|
||||||
@@ -228,9 +222,6 @@ pub struct Settings {
|
|||||||
pub wot_auto_trust: bool,
|
pub wot_auto_trust: bool,
|
||||||
/// Enable decoupling encryption key
|
/// Enable decoupling encryption key
|
||||||
pub nip4e: bool,
|
pub nip4e: bool,
|
||||||
/// Days between automatic encryption key rotations; None disables rotation
|
|
||||||
#[serde(default)]
|
|
||||||
pub nip4e_rotation_days: Option<u32>,
|
|
||||||
/// Hide the notice that messages in public groups are not encrypted
|
/// Hide the notice that messages in public groups are not encrypted
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub hide_group_notice: bool,
|
pub hide_group_notice: bool,
|
||||||
@@ -263,7 +254,6 @@ impl Default for Settings {
|
|||||||
screening: true,
|
screening: true,
|
||||||
wot_auto_trust: true,
|
wot_auto_trust: true,
|
||||||
nip4e: false,
|
nip4e: false,
|
||||||
nip4e_rotation_days: None,
|
|
||||||
hide_group_notice: false,
|
hide_group_notice: false,
|
||||||
theme: ThemeSettings::default(),
|
theme: ThemeSettings::default(),
|
||||||
panel_background: true,
|
panel_background: true,
|
||||||
@@ -340,40 +330,22 @@ impl AppSettings {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Apply the persisted theme tuning on top of the active theme
|
||||||
pub fn apply_theme_style(cx: &mut App) {
|
pub fn apply_theme_style(cx: &mut App) {
|
||||||
Self::apply_theme_tuning(Self::get_theme(cx), cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_theme_tuning(tuning: ThemeSettings, cx: &mut App) {
|
|
||||||
use gpui_kit::component::Theme;
|
use gpui_kit::component::Theme;
|
||||||
|
|
||||||
{
|
let theme = Self::get_theme(cx);
|
||||||
let styled = Theme::global_mut(cx);
|
let styled = Theme::global_mut(cx);
|
||||||
styled.font_size = px(tuning.font_size);
|
styled.font_size = px(theme.font_size);
|
||||||
styled.focus_ring = tuning.focus_ring;
|
styled.focus_ring = theme.focus_ring;
|
||||||
if let Some(radius) = tuning.radius {
|
if let Some(radius) = theme.radius {
|
||||||
styled.radius = px(radius);
|
styled.radius = px(radius);
|
||||||
}
|
}
|
||||||
if let Some(radius_lg) = tuning.radius_lg {
|
if let Some(radius_lg) = theme.radius_lg {
|
||||||
styled.radius_lg = px(radius_lg);
|
styled.radius_lg = px(radius_lg);
|
||||||
}
|
}
|
||||||
}
|
Theme::sync_base(cx);
|
||||||
|
cx.refresh_windows();
|
||||||
Theme::update(cx, |styled| {
|
|
||||||
let background = styled.background;
|
|
||||||
let foreground = styled.foreground;
|
|
||||||
let (hover_alpha, active_alpha) = if styled.is_dark() {
|
|
||||||
(0.08, 0.12)
|
|
||||||
} else {
|
|
||||||
(0.04, 0.06)
|
|
||||||
};
|
|
||||||
if styled.list_hover == background {
|
|
||||||
styled.list_hover = foreground.alpha(hover_alpha);
|
|
||||||
}
|
|
||||||
if styled.tab_active == background {
|
|
||||||
styled.tab_active = foreground.alpha(active_alpha);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load settings
|
/// Load settings
|
||||||
@@ -444,8 +416,7 @@ impl AppSettings {
|
|||||||
AppearanceMode::Light => Theme::change(gpui_kit::component::ThemeMode::Light, None, cx),
|
AppearanceMode::Light => Theme::change(gpui_kit::component::ThemeMode::Light, None, cx),
|
||||||
AppearanceMode::Dark => Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx),
|
AppearanceMode::Dark => Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx),
|
||||||
}
|
}
|
||||||
let tuning = self.inner.read(cx).theme;
|
cx.refresh_windows();
|
||||||
Self::apply_theme_tuning(tuning, cx);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if decoupling encryption key is enabled
|
/// Check if decoupling encryption key is enabled
|
||||||
|
|||||||
@@ -1,58 +1,33 @@
|
|||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use tts::Tts;
|
use tts::Tts;
|
||||||
|
|
||||||
/// Words per minute of an engine at its normal rate, for estimating speech duration.
|
|
||||||
const NORMAL_WPM: f32 = 160.0;
|
|
||||||
|
|
||||||
/// Extra time past the estimate before speech is considered finished, for backends that
|
|
||||||
/// cannot report utterance end.
|
|
||||||
pub const END_GRACE: Duration = Duration::from_secs(5);
|
|
||||||
|
|
||||||
/// Reads text aloud through the platform's speech backend, created on first use.
|
/// Reads text aloud through the platform's speech backend, created on first use.
|
||||||
pub struct Speaker {
|
pub struct Speaker {
|
||||||
tts: Option<Tts>,
|
tts: Option<Tts>,
|
||||||
end_tx: flume::Sender<()>,
|
}
|
||||||
end_rx: flume::Receiver<()>,
|
|
||||||
|
impl Default for Speaker {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Speaker {
|
impl Speaker {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let (end_tx, end_rx) = flume::unbounded();
|
Self { tts: None }
|
||||||
|
|
||||||
Self {
|
|
||||||
tts: None,
|
|
||||||
end_tx,
|
|
||||||
end_rx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Cloneable stream of utterance-finish events.
|
|
||||||
pub fn end_events(&self) -> flume::Receiver<()> {
|
|
||||||
self.end_rx.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Speak the text, interrupting what this speaker is already saying.
|
/// Speak the text, interrupting what this speaker is already saying.
|
||||||
pub fn speak(&mut self, text: &str) -> Result<Duration, tts::Error> {
|
pub fn speak(&mut self, text: &str) -> Result<(), tts::Error> {
|
||||||
let end_tx = self.end_tx.clone();
|
|
||||||
let tts = match self.tts.as_ref() {
|
let tts = match self.tts.as_ref() {
|
||||||
Some(tts) => tts,
|
Some(tts) => tts,
|
||||||
None => self.tts.insert({
|
None => self.tts.insert(Tts::default()?),
|
||||||
let tts = Tts::default()?;
|
|
||||||
if let Err(error) = tts.on_utterance_end(move |_| {
|
|
||||||
// A send error only means the panel dropped its event loop.
|
|
||||||
let _ = end_tx.send(());
|
|
||||||
}) {
|
|
||||||
log::warn!("utterance end events unavailable ({error})");
|
|
||||||
}
|
|
||||||
tts
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
tts.speak(text, true)?;
|
tts.speak(text, true)?;
|
||||||
Ok(Self::estimate(tts, text))
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stop speaking, a speaker that never spoke is already silent.
|
/// Stop speaking; a speaker that never spoke is already silent.
|
||||||
pub fn stop(&mut self) -> Result<(), tts::Error> {
|
pub fn stop(&mut self) -> Result<(), tts::Error> {
|
||||||
match self.tts.as_ref() {
|
match self.tts.as_ref() {
|
||||||
Some(tts) => tts.stop()?,
|
Some(tts) => tts.stop()?,
|
||||||
@@ -62,27 +37,11 @@ impl Speaker {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Best-effort speaking state, a speaker that never spoke is silent.
|
/// Best-effort speaking state; a speaker that never spoke is silent.
|
||||||
pub fn speaking(&self) -> bool {
|
pub fn speaking(&self) -> bool {
|
||||||
self.tts
|
self.tts
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|tts| tts.is_speaking().ok())
|
.and_then(|tts| tts.is_speaking().ok())
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How long speaking the text is expected to take at the engine's current speed.
|
|
||||||
fn estimate(tts: &Tts, text: &str) -> Duration {
|
|
||||||
let words = text.split_whitespace().count().max(1) as f32;
|
|
||||||
let speed = match (tts.get_rate(), tts.normal_rate()) {
|
|
||||||
(Ok(rate), Ok(normal)) if normal > 0. => (rate / normal).clamp(0.2, 4.),
|
|
||||||
_ => 1.,
|
|
||||||
};
|
|
||||||
Duration::from_secs_f32(words / NORMAL_WPM * 60. / speed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Speaker {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ use gpui::{App, AppContext as _, Task};
|
|||||||
|
|
||||||
use crate::USER_KEYRING;
|
use crate::USER_KEYRING;
|
||||||
|
|
||||||
/// The storage key for the log of handled NIP-4e key-sync request ids
|
/// The storage key for the NIP-4e app keys
|
||||||
const PROCESSED_REQUESTS_KEY: &str = "coop/nip4e/processed-requests";
|
const APP_KEYS_KEY: &str = "coop/nip4e/app-keys";
|
||||||
|
|
||||||
/// Read the stored credential as `(username, secret)`
|
/// Read the stored credential as `(username, secret)`
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
@@ -94,12 +94,12 @@ fn write_named(cx: &App, key: &str, secret: &[u8]) -> Task<Result<()>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read the log of handled key-sync request ids, as concatenated hex ids
|
/// Load the NIP-4e app keys from storage, as raw secret bytes
|
||||||
pub fn read_processed_requests(cx: &App) -> Task<Result<Option<Vec<u8>>>> {
|
pub fn read_app_keys(cx: &App) -> Task<Result<Option<Vec<u8>>>> {
|
||||||
read_named(cx, PROCESSED_REQUESTS_KEY)
|
read_named(cx, APP_KEYS_KEY)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Persist the log of handled key-sync request ids, as concatenated hex ids
|
/// Persist the NIP-4e app keys, as raw secret bytes
|
||||||
pub fn write_processed_requests(cx: &App, ids: &[u8]) -> Task<Result<()>> {
|
pub fn write_app_keys(cx: &App, secret: &[u8]) -> Task<Result<()>> {
|
||||||
write_named(cx, PROCESSED_REQUESTS_KEY, ids)
|
write_named(cx, APP_KEYS_KEY, secret)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ use nostr_sdk::prelude::*;
|
|||||||
pub struct Announcement {
|
pub struct Announcement {
|
||||||
/// The public key of the device that created this announcement.
|
/// The public key of the device that created this announcement.
|
||||||
public_key: PublicKey,
|
public_key: PublicKey,
|
||||||
/// The id of the announcement event, for ordering
|
|
||||||
event_id: EventId,
|
|
||||||
/// The creation time of the announcement event
|
|
||||||
created_at: Timestamp,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Announcement {
|
impl Announcement {
|
||||||
@@ -20,20 +16,11 @@ impl Announcement {
|
|||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
.and_then(|c| PublicKey::parse(c).ok())?;
|
.and_then(|c| PublicKey::parse(c).ok())?;
|
||||||
|
|
||||||
Some(Self {
|
Some(Self { public_key })
|
||||||
public_key,
|
|
||||||
event_id: event.id,
|
|
||||||
created_at: event.created_at,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the public key of the device that created this announcement.
|
/// Returns the public key of the device that created this announcement.
|
||||||
pub fn public_key(&self) -> PublicKey {
|
pub fn public_key(&self) -> PublicKey {
|
||||||
self.public_key
|
self.public_key
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_newer_than(&self, other: &Self) -> bool {
|
|
||||||
self.created_at > other.created_at
|
|
||||||
|| (self.created_at == other.created_at && self.event_id < other.event_id)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ pub enum IconName {
|
|||||||
Search,
|
Search,
|
||||||
Settings,
|
Settings,
|
||||||
Settings2,
|
Settings2,
|
||||||
Unlock,
|
|
||||||
Upload,
|
Upload,
|
||||||
Warning,
|
Warning,
|
||||||
}
|
}
|
||||||
@@ -64,7 +63,6 @@ impl IconNamed for IconName {
|
|||||||
Self::Search => "icons/search.svg",
|
Self::Search => "icons/search.svg",
|
||||||
Self::Settings => "icons/settings.svg",
|
Self::Settings => "icons/settings.svg",
|
||||||
Self::Settings2 => "icons/settings2.svg",
|
Self::Settings2 => "icons/settings2.svg",
|
||||||
Self::Unlock => "icons/unlock.svg",
|
|
||||||
Self::Upload => "icons/upload.svg",
|
Self::Upload => "icons/upload.svg",
|
||||||
Self::Warning => "icons/warning.svg",
|
Self::Warning => "icons/warning.svg",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,19 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use gpui::prelude::FluentBuilder as _;
|
use gpui::prelude::FluentBuilder as _;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Animation, AnimationExt as _, AnyElement, App, ClickEvent, Context, ElementId,
|
AnyElement, App, ClickEvent, Context, ElementId, InteractiveElement as _, IntoElement,
|
||||||
InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, ObjectFit,
|
MouseButton, MouseDownEvent, ObjectFit, ParentElement as _, RenderOnce, SharedString,
|
||||||
ParentElement as _, RenderOnce, SharedString, SharedUri, StatefulInteractiveElement as _,
|
SharedUri, StatefulInteractiveElement as _, StyleRefinement, Styled, StyledImage, Window, div,
|
||||||
StyleRefinement, Styled, StyledImage, Window, div, img, px,
|
img, px,
|
||||||
};
|
};
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||||
use gpui_kit::component::clipboard::Clipboard;
|
use gpui_kit::component::clipboard::Clipboard;
|
||||||
use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu, PopupMenuItem};
|
use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu, PopupMenuItem};
|
||||||
use gpui_kit::component::{
|
use gpui_kit::component::{
|
||||||
ActiveTheme, Disableable, InteractiveElementExt as _, Sizable as _, StyledExt as _, h_flex,
|
ActiveTheme, InteractiveElementExt as _, Sizable as _, StyledExt as _, h_flex, v_flex,
|
||||||
v_flex,
|
|
||||||
};
|
};
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
|
|
||||||
@@ -606,7 +604,7 @@ pub struct MessageActions {
|
|||||||
reactions: SmallVec<[(&'static str, SharedClickListener); 4]>,
|
reactions: SmallVec<[(&'static str, SharedClickListener); 4]>,
|
||||||
reply: Option<SharedClickListener>,
|
reply: Option<SharedClickListener>,
|
||||||
copy: Option<(ElementId, SharedString)>,
|
copy: Option<(ElementId, SharedString)>,
|
||||||
speech: Option<(bool, SharedClickListener)>,
|
speech: Option<SharedClickListener>,
|
||||||
dropdown: Option<DropdownBuilder>,
|
dropdown: Option<DropdownBuilder>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -646,13 +644,12 @@ impl MessageActions {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add the read-aloud button, disabled while a message is already being spoken.
|
/// Add the read-aloud button.
|
||||||
pub fn speech(
|
pub fn speech(
|
||||||
mut self,
|
mut self,
|
||||||
disabled: bool,
|
|
||||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
self.speech = Some((disabled, Rc::new(handler)));
|
self.speech = Some(Rc::new(handler));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -729,14 +726,13 @@ impl RenderOnce for MessageActions {
|
|||||||
.when_some(copy, |this, (id, value)| {
|
.when_some(copy, |this, (id, value)| {
|
||||||
this.child(Clipboard::new(id).value(value).tooltip("Copy").small())
|
this.child(Clipboard::new(id).value(value).tooltip("Copy").small())
|
||||||
})
|
})
|
||||||
.when_some(speech, |this, (disabled, speech)| {
|
.when_some(speech, |this, speech| {
|
||||||
this.child(
|
this.child(
|
||||||
Button::new("speech")
|
Button::new("speech")
|
||||||
.icon(crate::IconName::Speech)
|
.icon(crate::IconName::Speech)
|
||||||
.tooltip("Read aloud")
|
.tooltip("Read aloud")
|
||||||
.small()
|
.small()
|
||||||
.ghost()
|
.ghost()
|
||||||
.disabled(disabled)
|
|
||||||
.on_click(move |event, window, cx| speech(event, window, cx)),
|
.on_click(move |event, window, cx| speech(event, window, cx)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -754,44 +750,3 @@ impl RenderOnce for MessageActions {
|
|||||||
.refine_style(&style)
|
.refine_style(&style)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A message's text revealed word by word, paced by the estimated speech duration.
|
|
||||||
#[derive(IntoElement)]
|
|
||||||
pub struct RevealText {
|
|
||||||
text: SharedString,
|
|
||||||
duration: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RevealText {
|
|
||||||
pub fn new(text: impl Into<SharedString>, duration: Duration) -> Self {
|
|
||||||
Self {
|
|
||||||
text: text.into(),
|
|
||||||
duration,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderOnce for RevealText {
|
|
||||||
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
|
|
||||||
let words: Vec<SharedString> = self
|
|
||||||
.text
|
|
||||||
.split_whitespace()
|
|
||||||
.map(SharedString::from)
|
|
||||||
.collect();
|
|
||||||
let total = words.len().max(1) as f32;
|
|
||||||
|
|
||||||
div().flex().flex_wrap().gap_x_1().with_animation(
|
|
||||||
"speech-reveal",
|
|
||||||
Animation::new(self.duration).with_max_fps(30.),
|
|
||||||
move |this, progress| {
|
|
||||||
let visible = ((progress * total).ceil() as usize).min(words.len());
|
|
||||||
|
|
||||||
this.children(words.iter().enumerate().map(|(ix, word)| {
|
|
||||||
div()
|
|
||||||
.when(ix >= visible, |this| this.invisible())
|
|
||||||
.child(word.clone())
|
|
||||||
}))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,18 +1,15 @@
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
App, AppContext, Context, Div, Entity, IntoElement, ParentElement, Render, SharedString,
|
App, AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||||
Styled, Subscription, Task, Window, div, px, relative,
|
Subscription, Task, Window, div, px, relative,
|
||||||
};
|
};
|
||||||
use gpui_kit::component::button::{Button, ButtonVariants};
|
use gpui_kit::component::button::{Button, ButtonVariants};
|
||||||
use gpui_kit::component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
|
|
||||||
use gpui_kit::component::form::{field, v_form};
|
|
||||||
use gpui_kit::component::input::{Input, InputEvent, InputState};
|
use gpui_kit::component::input::{Input, InputEvent, InputState};
|
||||||
use gpui_kit::component::{ActiveTheme, Disableable, WindowExt, v_flex};
|
use gpui_kit::component::{ActiveTheme, Disableable, WindowExt, v_flex};
|
||||||
use instant::Duration;
|
use instant::Duration;
|
||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use state::{NostrRegistry, StateEvent};
|
use state::{NostrRegistry, StateEvent};
|
||||||
use ui::IconName;
|
|
||||||
|
|
||||||
pub fn open(window: &mut Window, cx: &mut App) {
|
pub fn open(window: &mut Window, cx: &mut App) {
|
||||||
let import = cx.new(|cx| ImportIdentity::new(window, cx));
|
let import = cx.new(|cx| ImportIdentity::new(window, cx));
|
||||||
@@ -35,6 +32,7 @@ pub fn open_unlock(window: &mut Window, cx: &mut App) {
|
|||||||
this.close_button(false)
|
this.close_button(false)
|
||||||
.overlay_closable(false)
|
.overlay_closable(false)
|
||||||
.keyboard(false)
|
.keyboard(false)
|
||||||
|
.title("Unlock your identity")
|
||||||
.child(import.clone())
|
.child(import.clone())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -76,15 +74,7 @@ impl ImportIdentity {
|
|||||||
fn build(mode: Mode, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
fn build(mode: Mode, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let key_input = cx.new(|cx| InputState::new(window, cx).placeholder("secret or bunker://"));
|
let key_input = cx.new(|cx| InputState::new(window, cx).placeholder("secret or bunker://"));
|
||||||
let pass_input = cx.new(|cx| {
|
let pass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||||
let input = InputState::new(window, cx).masked(true);
|
|
||||||
|
|
||||||
if mode == Mode::Unlock {
|
|
||||||
input.placeholder("Passphrase to unlock your identity")
|
|
||||||
} else {
|
|
||||||
input
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let repass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
let repass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||||
let error = cx.new(|_| None);
|
let error = cx.new(|_| None);
|
||||||
|
|
||||||
@@ -245,59 +235,15 @@ impl ImportIdentity {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_unlock(&self, cx: &mut Context<Self>) -> Div {
|
|
||||||
v_flex()
|
|
||||||
.gap_4()
|
|
||||||
.child(
|
|
||||||
DialogHeader::new()
|
|
||||||
.child(DialogTitle::new().child("Unlock your identity"))
|
|
||||||
.child(
|
|
||||||
DialogDescription::new()
|
|
||||||
.child("Enter the passphrase used to encrypt this identity."),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
v_form().child(
|
|
||||||
field()
|
|
||||||
.label("Passphrase")
|
|
||||||
.required(true)
|
|
||||||
.child(Input::new(&self.pass_input)),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
|
||||||
this.child(
|
|
||||||
div()
|
|
||||||
.text_sm()
|
|
||||||
.text_color(cx.theme().danger)
|
|
||||||
.child(error.clone()),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.child(
|
|
||||||
DialogFooter::new().child(
|
|
||||||
Button::new("unlock")
|
|
||||||
.primary()
|
|
||||||
.icon(IconName::Unlock)
|
|
||||||
.label("Unlock")
|
|
||||||
.loading(self.loading)
|
|
||||||
.disabled(self.loading)
|
|
||||||
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
|
||||||
this.login(cx);
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Render for ImportIdentity {
|
impl Render for ImportIdentity {
|
||||||
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
if self.mode == Mode::Unlock {
|
|
||||||
return self.render_unlock(cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
const BUNKER_WARN: &str = "Nostr Connect will usually take more time to get all your messages. Please keep your session open until you see all your messages.";
|
const BUNKER_WARN: &str = "Nostr Connect will usually take more time to get all your messages. Please keep your session open until you see all your messages.";
|
||||||
const KEY_WARN: &str = "Coop encrypts your key with your passphrase and stores it on this device. You only need the passphrase to sign in next time.";
|
const KEY_WARN: &str = "Coop encrypts your key with your passphrase and stores it on this device. You only need the passphrase to sign in next time.";
|
||||||
|
|
||||||
|
let is_unlock = self.mode == Mode::Unlock;
|
||||||
|
|
||||||
let value = self.key_input.read(cx).value().trim().to_string();
|
let value = self.key_input.read(cx).value().trim().to_string();
|
||||||
let require_password = value.starts_with("ncryptsec1");
|
let require_password = value.starts_with("ncryptsec1");
|
||||||
let require_encrypt = value.starts_with("nsec1");
|
let require_encrypt = value.starts_with("nsec1");
|
||||||
@@ -311,19 +257,25 @@ impl Render for ImportIdentity {
|
|||||||
.child(
|
.child(
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(
|
.when(!is_unlock, |this| {
|
||||||
|
this.child(
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_1()
|
.gap_1()
|
||||||
.text_color(cx.theme().muted_foreground)
|
.text_color(cx.theme().muted_foreground)
|
||||||
.child("Use secret key or bunker connection")
|
.child("Use secret key or bunker connection")
|
||||||
.child(Input::new(&self.key_input)),
|
.child(Input::new(&self.key_input)),
|
||||||
)
|
)
|
||||||
.when(require_password, |this| {
|
})
|
||||||
|
.when(is_unlock || require_password, |this| {
|
||||||
this.child(
|
this.child(
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_1()
|
.gap_1()
|
||||||
.text_color(cx.theme().muted_foreground)
|
.text_color(cx.theme().muted_foreground)
|
||||||
.child("Decrypt Password:")
|
.child(if is_unlock {
|
||||||
|
"Passphrase to unlock your identity:"
|
||||||
|
} else {
|
||||||
|
"Decrypt Password:"
|
||||||
|
})
|
||||||
.child(Input::new(&self.pass_input)),
|
.child(Input::new(&self.pass_input)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -371,7 +323,7 @@ impl Render for ImportIdentity {
|
|||||||
.child({
|
.child({
|
||||||
let content = v_flex().gap_1().child(
|
let content = v_flex().gap_1().child(
|
||||||
Button::new("login")
|
Button::new("login")
|
||||||
.label("Continue")
|
.label(if is_unlock { "Unlock" } else { "Continue" })
|
||||||
.primary()
|
.primary()
|
||||||
.loading(self.loading)
|
.loading(self.loading)
|
||||||
.disabled(self.loading)
|
.disabled(self.loading)
|
||||||
@@ -381,7 +333,8 @@ impl Render for ImportIdentity {
|
|||||||
);
|
);
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
let content = content.child(
|
let content = content.when(!is_unlock, |this| {
|
||||||
|
this.child(
|
||||||
Button::new("proxy")
|
Button::new("proxy")
|
||||||
.label("Connect via Web Extension")
|
.label("Connect via Web Extension")
|
||||||
.ghost()
|
.ghost()
|
||||||
@@ -389,10 +342,12 @@ impl Render for ImportIdentity {
|
|||||||
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
||||||
this.proxy(cx);
|
this.proxy(cx);
|
||||||
})),
|
})),
|
||||||
);
|
)
|
||||||
|
});
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
let content = content.child(
|
let content = content.when(!is_unlock, |this| {
|
||||||
|
this.child(
|
||||||
Button::new("extension")
|
Button::new("extension")
|
||||||
.label("Continue with Browser Extension")
|
.label("Continue with Browser Extension")
|
||||||
.ghost()
|
.ghost()
|
||||||
@@ -400,7 +355,8 @@ impl Render for ImportIdentity {
|
|||||||
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
||||||
this.extension(cx);
|
this.extension(cx);
|
||||||
})),
|
})),
|
||||||
);
|
)
|
||||||
|
});
|
||||||
|
|
||||||
content
|
content
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ use gpui_kit::component::progress::Progress;
|
|||||||
use gpui_kit::component::separator::Separator;
|
use gpui_kit::component::separator::Separator;
|
||||||
use gpui_kit::component::switch::Switch;
|
use gpui_kit::component::switch::Switch;
|
||||||
use gpui_kit::component::{Disableable, Sizable, WindowExt, h_flex, v_flex};
|
use gpui_kit::component::{Disableable, Sizable, WindowExt, h_flex, v_flex};
|
||||||
use settings::{AppSettings, AppearanceMode, NIP4E_ROTATION_DEFAULT_DAYS};
|
use settings::{AppSettings, AppearanceMode};
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use speech::model::{self as speech_model};
|
use speech::model::{self as speech_model};
|
||||||
use ui::{settings_block, settings_row};
|
use ui::{settings_block, settings_row};
|
||||||
@@ -337,7 +337,6 @@ impl Render for Preferences {
|
|||||||
"Corner radius for large elements like dialogs. Empty follows the OS theme.";
|
"Corner radius for large elements like dialogs. Empty follows the OS theme.";
|
||||||
const FOCUS_RING: &str = "Draw a ring around focused controls.";
|
const FOCUS_RING: &str = "Draw a ring around focused controls.";
|
||||||
const NIP4E: &str = "Use a dedicated key to encrypt and decrypt messages.";
|
const NIP4E: &str = "Use a dedicated key to encrypt and decrypt messages.";
|
||||||
const NIP4E_ROTATION: &str = "Automatically rotate the encryption key every 30 days, keeping the previous key for messages still sealed to it.";
|
|
||||||
const BACKGROUND: &str = "Show an image behind chat and group panels.";
|
const BACKGROUND: &str = "Show an image behind chat and group panels.";
|
||||||
const MEDIA: &str = "Server for media attachments. Only blossom services are supported.";
|
const MEDIA: &str = "Server for media attachments. Only blossom services are supported.";
|
||||||
|
|
||||||
@@ -345,7 +344,6 @@ impl Render for Preferences {
|
|||||||
let wot_auto_trust = AppSettings::get_wot_auto_trust(cx);
|
let wot_auto_trust = AppSettings::get_wot_auto_trust(cx);
|
||||||
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
||||||
let nip4e = AppSettings::get_nip4e(cx);
|
let nip4e = AppSettings::get_nip4e(cx);
|
||||||
let nip4e_rotation_days = AppSettings::get_nip4e_rotation_days(cx);
|
|
||||||
let appearance_mode = AppSettings::get_appearance_mode(cx);
|
let appearance_mode = AppSettings::get_appearance_mode(cx);
|
||||||
let theme = AppSettings::get_theme(cx);
|
let theme = AppSettings::get_theme(cx);
|
||||||
let panel_background = AppSettings::get_panel_background(cx);
|
let panel_background = AppSettings::get_panel_background(cx);
|
||||||
@@ -357,7 +355,7 @@ impl Render for Preferences {
|
|||||||
};
|
};
|
||||||
|
|
||||||
v_flex()
|
v_flex()
|
||||||
.my_2()
|
.mt_2()
|
||||||
.gap_4()
|
.gap_4()
|
||||||
.w_full()
|
.w_full()
|
||||||
.child(
|
.child(
|
||||||
@@ -509,22 +507,6 @@ impl Render for Preferences {
|
|||||||
}),
|
}),
|
||||||
cx,
|
cx,
|
||||||
))
|
))
|
||||||
.child(settings_row(
|
|
||||||
"Rotate Encryption Key",
|
|
||||||
NIP4E_ROTATION,
|
|
||||||
Switch::new("nip4e_rotation")
|
|
||||||
.checked(nip4e_rotation_days.is_some())
|
|
||||||
.on_click(move |_, _window, cx| {
|
|
||||||
let enabled = AppSettings::get_nip4e_rotation_days(cx).is_some();
|
|
||||||
let days = if enabled {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(NIP4E_ROTATION_DEFAULT_DAYS)
|
|
||||||
};
|
|
||||||
AppSettings::update_nip4e_rotation_days(days, cx);
|
|
||||||
}),
|
|
||||||
cx,
|
|
||||||
))
|
|
||||||
.child(Separator::horizontal())
|
.child(Separator::horizontal())
|
||||||
.child(self.render_speech(cx))
|
.child(self.render_speech(cx))
|
||||||
.child(self.render_dictation_shortcut(window, cx))
|
.child(self.render_dictation_shortcut(window, cx))
|
||||||
|
|||||||
@@ -91,12 +91,11 @@ impl Workspace {
|
|||||||
let workspace = cx.entity().downgrade();
|
let workspace = cx.entity().downgrade();
|
||||||
let mut subscriptions = smallvec![];
|
let mut subscriptions = smallvec![];
|
||||||
|
|
||||||
subscriptions.push(cx.observe_window_appearance(window, |_this, window, cx| {
|
|
||||||
if AppSettings::get_appearance_mode(cx) == AppearanceMode::System {
|
if AppSettings::get_appearance_mode(cx) == AppearanceMode::System {
|
||||||
|
subscriptions.push(cx.observe_window_appearance(window, |_this, window, cx| {
|
||||||
Theme::sync_system_appearance(Some(window), cx);
|
Theme::sync_system_appearance(Some(window), cx);
|
||||||
AppSettings::apply_theme_style(cx);
|
|
||||||
}
|
|
||||||
}));
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Subscribe to the nostr events
|
// Subscribe to the nostr events
|
||||||
|
|||||||
@@ -1,25 +1,18 @@
|
|||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use auto_update::AutoUpdater;
|
use auto_update::AutoUpdater;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
|
||||||
Anchor, App, Context, Div, InteractiveElement, IntoElement, ParentElement, SharedString,
|
|
||||||
Stateful, Styled, Window, div, px,
|
|
||||||
};
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use gpui::{AnyElement, Entity};
|
use gpui::{AnyElement, Entity, IntoElement};
|
||||||
use gpui_kit::base::StyledExt as _;
|
use gpui::{
|
||||||
|
App, Context, Div, InteractiveElement, ParentElement, Stateful, Styled, Window, div, px,
|
||||||
|
};
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use gpui_kit::component::Disableable;
|
use gpui_kit::component::Disableable;
|
||||||
use gpui_kit::component::button::{Button, ButtonVariant, ButtonVariants};
|
use gpui_kit::component::button::{Button, ButtonVariant, ButtonVariants};
|
||||||
use gpui_kit::component::clipboard::Clipboard;
|
|
||||||
use gpui_kit::component::dialog::DialogButtonProps;
|
use gpui_kit::component::dialog::DialogButtonProps;
|
||||||
use gpui_kit::component::menu::{DropdownMenu, PopupMenuItem};
|
use gpui_kit::component::menu::{DropdownMenu, PopupMenuItem};
|
||||||
use gpui_kit::component::popover::Popover;
|
|
||||||
use gpui_kit::component::separator::Separator;
|
|
||||||
use gpui_kit::component::{ActiveTheme, Icon, Selectable, Sizable, WindowExt, h_flex, v_flex};
|
use gpui_kit::component::{ActiveTheme, Icon, Selectable, Sizable, WindowExt, h_flex, v_flex};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::shorten_pubkey;
|
|
||||||
use settings::AppSettings;
|
|
||||||
use state::{CLIENT_NAME, NostrRegistry};
|
use state::{CLIENT_NAME, NostrRegistry};
|
||||||
use ui::{Avatar, IconName};
|
use ui::{Avatar, IconName};
|
||||||
|
|
||||||
@@ -38,10 +31,6 @@ impl Sidebar {
|
|||||||
let updater = AutoUpdater::try_global(cx);
|
let updater = AutoUpdater::try_global(cx);
|
||||||
let profile = self.directory.read(cx).person(current_user, cx);
|
let profile = self.directory.read(cx).person(current_user, cx);
|
||||||
let avatar = profile.avatar();
|
let avatar = profile.avatar();
|
||||||
let encryption_key = profile
|
|
||||||
.announcement()
|
|
||||||
.map(|announcement| announcement.public_key());
|
|
||||||
let encryption_enabled = AppSettings::get_nip4e(cx);
|
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.id("sidebar-user")
|
.id("sidebar-user")
|
||||||
@@ -82,11 +71,6 @@ impl Sidebar {
|
|||||||
});
|
});
|
||||||
|
|
||||||
actions
|
actions
|
||||||
.when(encryption_enabled, |actions| {
|
|
||||||
actions.when_some(encryption_key, |actions, encryption_key| {
|
|
||||||
actions.child(self.render_encryption(encryption_key))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.child(
|
.child(
|
||||||
Button::new("sidebar-search")
|
Button::new("sidebar-search")
|
||||||
.icon(IconName::Search)
|
.icon(IconName::Search)
|
||||||
@@ -127,89 +111,6 @@ impl Sidebar {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The encryption key popover: public key with copy, backup and reset
|
|
||||||
fn render_encryption(&self, encryption_key: PublicKey) -> impl IntoElement {
|
|
||||||
Popover::new("sidebar-encryption")
|
|
||||||
.anchor(Anchor::TopRight)
|
|
||||||
.trigger(
|
|
||||||
Button::new("encryption-key")
|
|
||||||
.icon(IconName::Lock)
|
|
||||||
.tooltip("Encryption Key")
|
|
||||||
.ghost()
|
|
||||||
.small(),
|
|
||||||
)
|
|
||||||
.content(move |_, _, cx| {
|
|
||||||
let popover = cx.entity();
|
|
||||||
let Ok(npub) = encryption_key.to_bech32();
|
|
||||||
|
|
||||||
v_flex()
|
|
||||||
.w_64()
|
|
||||||
.gap_2()
|
|
||||||
.text_sm()
|
|
||||||
.child(
|
|
||||||
div()
|
|
||||||
.text_xs()
|
|
||||||
.font_semibold()
|
|
||||||
.text_color(cx.theme().muted_foreground)
|
|
||||||
.child("Public key"),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
h_flex()
|
|
||||||
.items_center()
|
|
||||||
.gap_1()
|
|
||||||
.child(
|
|
||||||
div()
|
|
||||||
.flex_1()
|
|
||||||
.min_w_0()
|
|
||||||
.truncate()
|
|
||||||
.text_color(cx.theme().muted_foreground)
|
|
||||||
.child(SharedString::from(shorten_pubkey(encryption_key, 12))),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
Clipboard::new("encryption-key-copy")
|
|
||||||
.tooltip("Copy public key")
|
|
||||||
.value(npub),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.child(Separator::horizontal())
|
|
||||||
.child(
|
|
||||||
h_flex()
|
|
||||||
.justify_end()
|
|
||||||
.gap_2()
|
|
||||||
.child(
|
|
||||||
Button::new("encryption-backup")
|
|
||||||
.label("Backup")
|
|
||||||
.outline()
|
|
||||||
.small()
|
|
||||||
.on_click({
|
|
||||||
let popover = popover.clone();
|
|
||||||
move |_, window, cx| {
|
|
||||||
popover
|
|
||||||
.update(cx, |state, cx| state.dismiss(window, cx));
|
|
||||||
window.dispatch_action(
|
|
||||||
Box::new(Command::BackupEncryption),
|
|
||||||
cx,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
Button::new("encryption-reset")
|
|
||||||
.label("Reset")
|
|
||||||
.ghost()
|
|
||||||
.small()
|
|
||||||
.on_click(move |_, window, cx| {
|
|
||||||
popover.update(cx, |state, cx| state.dismiss(window, cx));
|
|
||||||
window.dispatch_action(
|
|
||||||
Box::new(Command::ResetEncryption),
|
|
||||||
cx,
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn render_footer(&self, loading: bool, _cx: &mut Context<Self>) -> Div {
|
pub(super) fn render_footer(&self, loading: bool, _cx: &mut Context<Self>) -> Div {
|
||||||
v_flex()
|
v_flex()
|
||||||
.p_2()
|
.p_2()
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ use nostr_sdk::prelude::*;
|
|||||||
use person::{Directory, PersonRegistry};
|
use person::{Directory, PersonRegistry};
|
||||||
pub(crate) use rows::open_room;
|
pub(crate) use rows::open_room;
|
||||||
use search::SearchResult;
|
use search::SearchResult;
|
||||||
use settings::AppSettings;
|
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{FIND_DELAY, NostrRegistry, StateEvent};
|
use state::{FIND_DELAY, NostrRegistry, StateEvent};
|
||||||
use ui::title_bar_drag_handlers;
|
use ui::title_bar_drag_handlers;
|
||||||
@@ -105,8 +104,6 @@ impl Sidebar {
|
|||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
let groups = GroupsRegistry::global(cx);
|
let groups = GroupsRegistry::global(cx);
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let settings = AppSettings::global(cx);
|
|
||||||
let directory = Directory::new(cx);
|
|
||||||
|
|
||||||
let find_input = cx.new(|cx| {
|
let find_input = cx.new(|cx| {
|
||||||
InputState::new(window, cx)
|
InputState::new(window, cx)
|
||||||
@@ -209,11 +206,6 @@ impl Sidebar {
|
|||||||
},
|
},
|
||||||
));
|
));
|
||||||
|
|
||||||
// The user header reads settings and the tracked profiles on render, so
|
|
||||||
// the encryption button reacts to toggles and announcement arrivals
|
|
||||||
subscriptions.push(cx.observe(&settings, |_, _, cx| cx.notify()));
|
|
||||||
subscriptions.push(cx.observe(&directory, |_, _, cx| cx.notify()));
|
|
||||||
|
|
||||||
tasks.push(cx.spawn(async move |this, cx| {
|
tasks.push(cx.spawn(async move |this, cx| {
|
||||||
let timer = Duration::from_millis(PROGRESS_TICK_MS);
|
let timer = Duration::from_millis(PROGRESS_TICK_MS);
|
||||||
loop {
|
loop {
|
||||||
@@ -237,7 +229,7 @@ impl Sidebar {
|
|||||||
chats_open: None,
|
chats_open: None,
|
||||||
contacts_open: false,
|
contacts_open: false,
|
||||||
contacts: None,
|
contacts: None,
|
||||||
directory,
|
directory: Directory::new(cx),
|
||||||
selected_contacts: HashSet::new(),
|
selected_contacts: HashSet::new(),
|
||||||
requests_open: false,
|
requests_open: false,
|
||||||
new_requests: false,
|
new_requests: false,
|
||||||
|
|||||||
+11
-4
@@ -72,13 +72,14 @@ fn main() {
|
|||||||
|
|
||||||
let appearance = settings::persisted_appearance_mode();
|
let appearance = settings::persisted_appearance_mode();
|
||||||
let font_size = settings::persisted_theme().font_size;
|
let font_size = settings::persisted_theme().font_size;
|
||||||
|
match apply_native_theme(appearance, font_size, cx) {
|
||||||
if let Err(error) = apply_native_theme(appearance, font_size, cx) {
|
Ok(()) => start_theme_watcher(appearance, cx),
|
||||||
|
Err(error) => {
|
||||||
log::warn!("native theme unavailable ({error})");
|
log::warn!("native theme unavailable ({error})");
|
||||||
apply_appearance(appearance, cx);
|
apply_appearance(appearance, cx);
|
||||||
AppSettings::apply_theme_style(cx);
|
AppSettings::apply_theme_style(cx);
|
||||||
}
|
}
|
||||||
start_theme_watcher(cx);
|
}
|
||||||
|
|
||||||
// Initialize the nostr client
|
// Initialize the nostr client
|
||||||
state::init(cx, cli_key);
|
state::init(cx, cli_key);
|
||||||
@@ -212,12 +213,14 @@ fn apply_appearance(appearance: AppearanceMode, cx: &mut App) {
|
|||||||
/// Holds the watcher subscription so it lives as long as the app.
|
/// Holds the watcher subscription so it lives as long as the app.
|
||||||
struct ThemeWatcher {
|
struct ThemeWatcher {
|
||||||
_subscription: ThemeSubscription,
|
_subscription: ThemeSubscription,
|
||||||
|
/// The appearance mode the observer in `workspace` was registered with.
|
||||||
|
appearance: std::cell::Cell<AppearanceMode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Global for ThemeWatcher {}
|
impl Global for ThemeWatcher {}
|
||||||
|
|
||||||
/// Start a background task to watch for OS theme changes and re-apply the native theme.
|
/// Start a background task to watch for OS theme changes and re-apply the native theme.
|
||||||
fn start_theme_watcher(cx: &mut App) {
|
fn start_theme_watcher(initial_appearance: AppearanceMode, cx: &mut App) {
|
||||||
let (sender, receiver) = flume::unbounded();
|
let (sender, receiver) = flume::unbounded();
|
||||||
match native_theme::watch::on_theme_change(move |event| {
|
match native_theme::watch::on_theme_change(move |event| {
|
||||||
if let Err(error) = sender.send(event) {
|
if let Err(error) = sender.send(event) {
|
||||||
@@ -227,6 +230,7 @@ fn start_theme_watcher(cx: &mut App) {
|
|||||||
Ok(subscription) => {
|
Ok(subscription) => {
|
||||||
cx.set_global(ThemeWatcher {
|
cx.set_global(ThemeWatcher {
|
||||||
_subscription: subscription,
|
_subscription: subscription,
|
||||||
|
appearance: std::cell::Cell::new(initial_appearance),
|
||||||
});
|
});
|
||||||
cx.spawn(async move |cx| {
|
cx.spawn(async move |cx| {
|
||||||
while receiver.recv_async().await.is_ok() {
|
while receiver.recv_async().await.is_ok() {
|
||||||
@@ -234,6 +238,9 @@ fn start_theme_watcher(cx: &mut App) {
|
|||||||
cx.update(|cx| {
|
cx.update(|cx| {
|
||||||
let appearance = AppSettings::get_appearance_mode(cx);
|
let appearance = AppSettings::get_appearance_mode(cx);
|
||||||
let font_size = AppSettings::get_theme(cx).font_size;
|
let font_size = AppSettings::get_theme(cx).font_size;
|
||||||
|
if let Some(watcher) = cx.try_global::<ThemeWatcher>() {
|
||||||
|
watcher.appearance.set(appearance);
|
||||||
|
}
|
||||||
if let Err(error) = apply_native_theme(appearance, font_size, cx) {
|
if let Err(error) = apply_native_theme(appearance, font_size, cx) {
|
||||||
log::warn!("failed to apply updated OS theme ({error})");
|
log::warn!("failed to apply updated OS theme ({error})");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,12 +21,12 @@ if [[ "$1" == "--release" ]]; then
|
|||||||
echo -e "${YELLOW}Building in release mode${NC}"
|
echo -e "${YELLOW}Building in release mode${NC}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
NIGHTLY="nightly-2026-10-31"
|
# wasm_thread requires a nightly compiler for its atomics features
|
||||||
CARGO="cargo +$NIGHTLY"
|
CARGO="cargo +nightly"
|
||||||
|
|
||||||
# Step 0: Toolchain prerequisites
|
# Step 0: Toolchain prerequisites
|
||||||
echo -e "${GREEN}Step 0: Checking toolchain...${NC}"
|
echo -e "${GREEN}Step 0: Checking toolchain...${NC}"
|
||||||
rustup target add wasm32-unknown-unknown --toolchain "$NIGHTLY"
|
rustup target add wasm32-unknown-unknown --toolchain nightly
|
||||||
|
|
||||||
if [[ "$(uname)" == "Darwin" ]]; then
|
if [[ "$(uname)" == "Darwin" ]]; then
|
||||||
# secp256k1-sys compiles C for wasm; Apple clang has the wasm32 target and
|
# secp256k1-sys compiles C for wasm; Apple clang has the wasm32 target and
|
||||||
@@ -35,7 +35,7 @@ if [[ "$(uname)" == "Darwin" ]]; then
|
|||||||
echo -e "${RED}Apple clang not found. Install the Xcode command line tools: xcode-select --install${NC}"
|
echo -e "${RED}Apple clang not found. Install the Xcode command line tools: xcode-select --install${NC}"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
rustup component add llvm-tools-preview --toolchain "$NIGHTLY"
|
rustup component add llvm-tools-preview --toolchain nightly
|
||||||
|
|
||||||
RUSTUP_HOME=$(rustup show home)
|
RUSTUP_HOME=$(rustup show home)
|
||||||
if [[ "$(uname -m)" == "arm64" ]]; then
|
if [[ "$(uname -m)" == "arm64" ]]; then
|
||||||
@@ -43,7 +43,7 @@ if [[ "$(uname)" == "Darwin" ]]; then
|
|||||||
else
|
else
|
||||||
HOST_ARCH="x86_64-apple-darwin"
|
HOST_ARCH="x86_64-apple-darwin"
|
||||||
fi
|
fi
|
||||||
LLVM_BIN="$RUSTUP_HOME/toolchains/$NIGHTLY-$HOST_ARCH/lib/rustlib/$HOST_ARCH/bin"
|
LLVM_BIN="$RUSTUP_HOME/toolchains/nightly-$HOST_ARCH/lib/rustlib/$HOST_ARCH/bin"
|
||||||
|
|
||||||
export CC_wasm32_unknown_unknown=clang
|
export CC_wasm32_unknown_unknown=clang
|
||||||
export AR_wasm32_unknown_unknown="$LLVM_BIN/llvm-ar"
|
export AR_wasm32_unknown_unknown="$LLVM_BIN/llvm-ar"
|
||||||
|
|||||||
Reference in New Issue
Block a user