From 407fe40b67832fa2df3e44d7e2f3edce93d49331 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=9B=A8=E5=AE=AE=E8=93=AE?=
<123083837+reyamir@users.noreply.github.com>
Date: Wed, 22 May 2024 13:24:58 +0700
Subject: [PATCH] refactor: account managements (#190)
* feat: add keyring-search
* feat: improve nostr connect
---
apps/desktop2/src/routes/$account.tsx | 4 +-
apps/desktop2/src/routes/auth/remote.lazy.tsx | 23 ++-
apps/desktop2/src/routes/index.tsx | 4 +-
apps/desktop2/src/routes/settings/backup.tsx | 2 +-
packages/ark/src/ark.ts | 22 +-
src-tauri/Cargo.lock | 16 ++
src-tauri/Cargo.toml | 3 +-
src-tauri/src/commands/folder.rs | 24 ---
src-tauri/src/main.rs | 9 +-
src-tauri/src/nostr/keys.rs | 189 +++++++++---------
10 files changed, 153 insertions(+), 143 deletions(-)
diff --git a/apps/desktop2/src/routes/$account.tsx b/apps/desktop2/src/routes/$account.tsx
index 33a6d06d1..f3b891242 100644
--- a/apps/desktop2/src/routes/$account.tsx
+++ b/apps/desktop2/src/routes/$account.tsx
@@ -23,7 +23,7 @@ import * as Popover from "@radix-ui/react-popover";
export const Route = createFileRoute("/$account")({
beforeLoad: async ({ context }) => {
const ark = context.ark;
- const accounts = await ark.get_all_accounts();
+ const accounts = await ark.get_accounts();
return { accounts };
},
@@ -106,7 +106,7 @@ function Accounts() {
}
// change current account and update signer
- const select = await ark.load_selected_account(npub);
+ const select = await ark.load_account(npub);
if (select) {
return navigate({ to: "/$account/home", params: { account: npub } });
diff --git a/apps/desktop2/src/routes/auth/remote.lazy.tsx b/apps/desktop2/src/routes/auth/remote.lazy.tsx
index 931fca9d1..62c5ba014 100644
--- a/apps/desktop2/src/routes/auth/remote.lazy.tsx
+++ b/apps/desktop2/src/routes/auth/remote.lazy.tsx
@@ -60,14 +60,21 @@ function Screen() {
className="h-11 rounded-lg border-transparent bg-neutral-100 px-3 placeholder:text-neutral-600 focus:border-blue-500 focus:ring-0 dark:bg-white/10 dark:placeholder:text-neutral-400"
/>
-
+
+
+ {loading ? (
+
+ Waiting confirmation...
+
+ ) : null}
+
);
diff --git a/apps/desktop2/src/routes/index.tsx b/apps/desktop2/src/routes/index.tsx
index a312e91cd..80d7ea155 100644
--- a/apps/desktop2/src/routes/index.tsx
+++ b/apps/desktop2/src/routes/index.tsx
@@ -14,7 +14,7 @@ export const Route = createFileRoute("/")({
await checkForAppUpdates(true);
const ark = context.ark;
- const accounts = await ark.get_all_accounts();
+ const accounts = await ark.get_accounts();
if (!accounts.length) {
throw redirect({
@@ -41,7 +41,7 @@ function Screen() {
try {
setLoading(true);
- const loadAccount = await ark.load_selected_account(npub);
+ const loadAccount = await ark.load_account(npub);
if (loadAccount) {
return navigate({
to: "/$account/home",
diff --git a/apps/desktop2/src/routes/settings/backup.tsx b/apps/desktop2/src/routes/settings/backup.tsx
index a91a2d3cd..90a94e56f 100644
--- a/apps/desktop2/src/routes/settings/backup.tsx
+++ b/apps/desktop2/src/routes/settings/backup.tsx
@@ -11,7 +11,7 @@ export const Route = createFileRoute("/settings/backup")({
component: Screen,
loader: async ({ context }) => {
const ark = context.ark;
- const npubs = await ark.get_all_accounts();
+ const npubs = await ark.get_accounts();
const accounts: Account[] = [];
diff --git a/packages/ark/src/ark.ts b/packages/ark/src/ark.ts
index 3aa0dfe82..6c875acb0 100644
--- a/packages/ark/src/ark.ts
+++ b/packages/ark/src/ark.ts
@@ -29,22 +29,26 @@ export class Ark {
this.settings = undefined;
}
- public async get_all_accounts() {
+ public async get_accounts() {
try {
- const cmd: string[] = await invoke("get_accounts");
- const accounts: string[] = cmd.map((item) => item.replace(".npub", ""));
+ const cmd: string = await invoke("get_accounts");
+ const parse = cmd.split(/\s+/).filter((v) => v.startsWith("npub1"));
+ const accounts = [...new Set(parse)];
- if (!this.accounts) this.accounts = accounts;
+ if (!this.accounts) {
+ this.accounts = accounts;
+ }
return accounts;
} catch (e) {
- throw new Error(String(e));
+ console.info(String(e));
+ return [];
}
}
- public async load_selected_account(npub: string) {
+ public async load_account(npub: string) {
try {
- const cmd: boolean = await invoke("load_selected_account", {
+ const cmd: boolean = await invoke("load_account", {
npub,
});
return cmd;
@@ -73,7 +77,7 @@ export class Ark {
public async create_keys() {
try {
- const cmd: Keys = await invoke("create_keys");
+ const cmd: Keys = await invoke("create_account");
return cmd;
} catch (e) {
console.error(String(e));
@@ -82,7 +86,7 @@ export class Ark {
public async save_account(nsec: string, password = "") {
try {
- const cmd: string = await invoke("save_key", {
+ const cmd: string = await invoke("save_account", {
nsec,
password,
});
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index ac26baf98..b933532a9 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2668,6 +2668,21 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "keyring-search"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95edd18bc5d51d3544a788d86b6d96c20b3fea5518349559df1feaa4775fc632"
+dependencies = [
+ "byteorder",
+ "lazy_static",
+ "linux-keyutils",
+ "regex",
+ "secret-service",
+ "security-framework",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "kuchikiki"
version = "0.8.2"
@@ -2862,6 +2877,7 @@ version = "4.0.0"
dependencies = [
"cocoa",
"keyring",
+ "keyring-search",
"nostr-sdk",
"objc",
"rand 0.8.5",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 65b4ecd15..543c1a920 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -33,9 +33,10 @@ tauri-plugin-shell = "2.0.0-beta"
tauri-plugin-updater = "2.0.0-beta"
tauri-plugin-upload = "2.0.0-beta"
tauri-plugin-window-state = "2.0.0-beta"
+tauri-plugin-decorum = "0.1.0"
webpage = { version = "2.0", features = ["serde"] }
keyring = "2"
-tauri-plugin-decorum = "0.1.0"
+keyring-search = "0.2.0"
[target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.25.0"
diff --git a/src-tauri/src/commands/folder.rs b/src-tauri/src/commands/folder.rs
index 723d1895d..2bea7d0b5 100644
--- a/src-tauri/src/commands/folder.rs
+++ b/src-tauri/src/commands/folder.rs
@@ -1,5 +1,4 @@
use std::process::Command;
-use tauri::Manager;
#[tauri::command]
pub async fn show_in_folder(path: String) {
@@ -47,26 +46,3 @@ pub async fn show_in_folder(path: String) {
Command::new("open").args(["-R", &path]).spawn().unwrap();
}
}
-
-#[tauri::command]
-pub fn get_accounts(app_handle: tauri::AppHandle) -> Result, ()> {
- let dir = app_handle.path().home_dir().unwrap();
-
- if let Ok(paths) = std::fs::read_dir(dir.join("Lume/")) {
- let files = paths
- .filter_map(|res| res.ok())
- .map(|dir_entry| dir_entry.path())
- .filter_map(|path| {
- if path.extension().map_or(false, |ext| ext == "npub") {
- Some(path.file_name().unwrap().to_str().unwrap().to_string())
- } else {
- None
- }
- })
- .collect::>();
-
- Ok(files)
- } else {
- Err(())
- }
-}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index f2cd87f2a..962c0a293 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -102,12 +102,12 @@ fn main() {
nostr::relay::get_relays,
nostr::relay::connect_relay,
nostr::relay::remove_relay,
- nostr::keys::create_keys,
- nostr::keys::save_key,
+ nostr::keys::get_accounts,
+ nostr::keys::create_account,
+ nostr::keys::save_account,
nostr::keys::get_encrypted_key,
- nostr::keys::get_stored_nsec,
nostr::keys::nostr_connect,
- nostr::keys::load_selected_account,
+ nostr::keys::load_account,
nostr::keys::event_to_bech32,
nostr::keys::user_to_bech32,
nostr::keys::to_npub,
@@ -139,7 +139,6 @@ fn main() {
nostr::event::publish,
nostr::event::repost,
commands::folder::show_in_folder,
- commands::folder::get_accounts,
commands::window::create_column,
commands::window::close_column,
commands::window::reposition_column,
diff --git a/src-tauri/src/nostr/keys.rs b/src-tauri/src/nostr/keys.rs
index 76ef59e96..7650e8c38 100644
--- a/src-tauri/src/nostr/keys.rs
+++ b/src-tauri/src/nostr/keys.rs
@@ -1,35 +1,46 @@
use crate::Nostr;
use keyring::Entry;
+use keyring_search::{Limit, List, Search};
use nostr_sdk::prelude::*;
+use std::str::FromStr;
use std::time::Duration;
-use std::{fs::File, str::FromStr};
-use tauri::{Manager, State};
+use tauri::State;
#[derive(serde::Serialize)]
-pub struct CreateKeysResponse {
+pub struct Account {
npub: String,
nsec: String,
}
#[tauri::command]
-pub fn create_keys() -> Result {
+pub fn get_accounts() -> Result {
+ let search = Search::new().unwrap();
+ let results = search.by("Account", "nostr_secret");
+
+ match List::list_credentials(results, Limit::All) {
+ Ok(list) => Ok(list),
+ Err(_) => Err("Empty.".into()),
+ }
+}
+
+#[tauri::command]
+pub fn create_account() -> Result {
let keys = Keys::generate();
let public_key = keys.public_key();
- let secret_key = keys.secret_key().expect("secret key failed");
+ let secret_key = keys.secret_key().unwrap();
- let result = CreateKeysResponse {
- npub: public_key.to_bech32().expect("npub failed"),
- nsec: secret_key.to_bech32().expect("nsec failed"),
+ let result = Account {
+ npub: public_key.to_bech32().unwrap(),
+ nsec: secret_key.to_bech32().unwrap(),
};
Ok(result)
}
#[tauri::command]
-pub async fn save_key(
+pub async fn save_account(
nsec: &str,
password: &str,
- app_handle: tauri::AppHandle,
state: State<'_, Nostr>,
) -> Result {
let secret_key: Result;
@@ -38,12 +49,12 @@ pub async fn save_key(
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
secret_key = match encrypted_key.to_secret_key(password) {
Ok(val) => Ok(val),
- Err(_) => Err("Wrong passphase".into()),
+ Err(err) => Err(err.to_string()),
};
} else {
secret_key = match SecretKey::from_bech32(nsec) {
Ok(val) => Ok(val),
- Err(_) => Err("nsec is not valid".into()),
+ Err(err) => Err(err.to_string()),
}
}
@@ -53,13 +64,7 @@ pub async fn save_key(
let npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
- let home_dir = app_handle.path().home_dir().unwrap();
- let app_dir = home_dir.join("Lume/");
-
- let file_path = npub.clone() + ".npub";
- let _ = File::create(app_dir.join(file_path)).unwrap();
-
- let keyring = Entry::new("Lume Secret Storage", &npub).unwrap();
+ let keyring = Entry::new(&npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(nostr_keys);
@@ -75,83 +80,29 @@ pub async fn save_key(
}
#[tauri::command]
-pub async fn nostr_connect(
- npub: &str,
- uri: &str,
- app_handle: tauri::AppHandle,
- state: State<'_, Nostr>,
-) -> Result {
- let client = &state.client;
- let app_keys = Keys::generate();
-
- match NostrConnectURI::parse(uri) {
- Ok(bunker_uri) => {
- println!("connecting... {}", uri);
-
- match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await {
- Ok(signer) => {
- let home_dir = app_handle.path().home_dir().unwrap();
- let app_dir = home_dir.join("Lume/");
- let file_path = npub.to_owned() + ".npub";
- let keyring = Entry::new("Lume Secret Storage", npub).unwrap();
- let _ = File::create(app_dir.join(file_path)).unwrap();
- let _ = keyring.set_password(uri);
- let _ = client.set_signer(Some(signer.into())).await;
-
- Ok(npub.into())
- }
- Err(err) => Err(err.to_string()),
- }
- }
- Err(err) => Err(err.to_string()),
- }
-}
-
-#[tauri::command(async)]
-pub fn get_encrypted_key(npub: &str, password: &str) -> Result {
- let keyring = Entry::new("Lume Secret Storage", npub).unwrap();
-
- if let Ok(nsec) = keyring.get_password() {
- let secret_key = SecretKey::from_bech32(nsec).expect("Get secret key failed");
- let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Unknown);
-
- if let Ok(key) = new_key {
- Ok(key.to_bech32().unwrap())
- } else {
- Err("Encrypt key failed".into())
- }
- } else {
- Err("Key not found".into())
- }
-}
-
-#[tauri::command]
-pub fn get_stored_nsec(npub: &str) -> Result {
- let keyring = Entry::new("Lume Secret Storage", npub).unwrap();
-
- if let Ok(nsec) = keyring.get_password() {
- Ok(nsec)
- } else {
- Err("Key not found".into())
- }
-}
-
-#[tauri::command]
-pub async fn load_selected_account(npub: &str, state: State<'_, Nostr>) -> Result {
+pub async fn load_account(npub: &str, state: State<'_, Nostr>) -> Result {
let client = &state.client;
- let keyring = Entry::new("Lume Secret Storage", npub).unwrap();
+ let keyring = Entry::new(&npub, "nostr_secret").unwrap();
match keyring.get_password() {
Ok(password) => {
if password.starts_with("bunker://") {
- let app_keys = Keys::generate();
- let bunker_uri = NostrConnectURI::parse(password).unwrap();
- let signer = Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(60), None)
- .await
- .unwrap();
-
- // Update signer
- client.set_signer(Some(signer.into())).await;
+ let local_keyring = Entry::new(&npub, "bunker_local_account").unwrap();
+
+ match local_keyring.get_password() {
+ Ok(local_password) => {
+ let secret_key = SecretKey::from_bech32(local_password).unwrap();
+ let app_keys = Keys::new(secret_key);
+ let bunker_uri = NostrConnectURI::parse(password).unwrap();
+ let signer = Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(60), None)
+ .await
+ .unwrap();
+
+ // Update signer
+ client.set_signer(Some(signer.into())).await;
+ }
+ Err(_) => todo!(),
+ }
} else {
let secret_key = SecretKey::from_bech32(password).expect("Get secret key failed");
let keys = Keys::new(secret_key);
@@ -213,6 +164,62 @@ pub async fn load_selected_account(npub: &str, state: State<'_, Nostr>) -> Resul
}
}
+#[tauri::command]
+pub async fn nostr_connect(
+ npub: &str,
+ uri: &str,
+ state: State<'_, Nostr>,
+) -> Result {
+ let client = &state.client;
+ let local_key = Keys::generate();
+
+ match NostrConnectURI::parse(uri) {
+ Ok(bunker_uri) => {
+ match Nip46Signer::new(
+ bunker_uri,
+ local_key.clone(),
+ Duration::from_secs(120),
+ None,
+ )
+ .await
+ {
+ Ok(signer) => {
+ let local_secret = local_key.secret_key().unwrap().to_bech32().unwrap();
+ let secret_keyring = Entry::new(&npub, "nostr_secret").unwrap();
+ let account_keyring = Entry::new(&npub, "bunker_local_account").unwrap();
+ let _ = secret_keyring.set_password(uri);
+ let _ = account_keyring.set_password(&local_secret);
+
+ // Update signer
+ let _ = client.set_signer(Some(signer.into())).await;
+
+ Ok(npub.into())
+ }
+ Err(err) => Err(err.to_string()),
+ }
+ }
+ Err(err) => Err(err.to_string()),
+ }
+}
+
+#[tauri::command(async)]
+pub fn get_encrypted_key(npub: &str, password: &str) -> Result {
+ let keyring = Entry::new(npub, "nostr_secret").unwrap();
+
+ if let Ok(nsec) = keyring.get_password() {
+ let secret_key = SecretKey::from_bech32(nsec).unwrap();
+ let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Medium);
+
+ if let Ok(key) = new_key {
+ Ok(key.to_bech32().unwrap())
+ } else {
+ Err("Encrypt key failed".into())
+ }
+ } else {
+ Err("Key not found".into())
+ }
+}
+
#[tauri::command]
pub fn event_to_bech32(id: &str, relays: Vec) -> Result {
let event_id = EventId::from_hex(id).unwrap();