refactor: account managements (#190)

* feat: add keyring-search

* feat: improve nostr connect
This commit is contained in:
雨宮蓮
2024-05-22 13:24:58 +07:00
committed by GitHub
parent 1f38eba2cc
commit 407fe40b67
10 changed files with 152 additions and 142 deletions

View File

@@ -23,7 +23,7 @@ import * as Popover from "@radix-ui/react-popover";
export const Route = createFileRoute("/$account")({ export const Route = createFileRoute("/$account")({
beforeLoad: async ({ context }) => { beforeLoad: async ({ context }) => {
const ark = context.ark; const ark = context.ark;
const accounts = await ark.get_all_accounts(); const accounts = await ark.get_accounts();
return { accounts }; return { accounts };
}, },
@@ -106,7 +106,7 @@ function Accounts() {
} }
// change current account and update signer // change current account and update signer
const select = await ark.load_selected_account(npub); const select = await ark.load_account(npub);
if (select) { if (select) {
return navigate({ to: "/$account/home", params: { account: npub } }); return navigate({ to: "/$account/home", params: { account: npub } });

View File

@@ -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" 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"
/> />
</div> </div>
<button <div className="flex flex-col gap-1 items-center">
type="button" <button
onClick={() => submit()} type="button"
disabled={loading} onClick={() => submit()}
className="mt-3 inline-flex h-11 w-full shrink-0 items-center justify-center rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600 disabled:opacity-50" disabled={loading}
> className="mt-3 inline-flex h-11 w-full shrink-0 items-center justify-center rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600 disabled:opacity-50"
{loading ? <Spinner /> : "Login"} >
</button> {loading ? <Spinner /> : "Login"}
</button>
{loading ? (
<p className="text-neutral-600 dark:text-neutral-400 text-sm text-center">
Waiting confirmation...
</p>
) : null}
</div>
</div> </div>
</div> </div>
); );

View File

@@ -14,7 +14,7 @@ export const Route = createFileRoute("/")({
await checkForAppUpdates(true); await checkForAppUpdates(true);
const ark = context.ark; const ark = context.ark;
const accounts = await ark.get_all_accounts(); const accounts = await ark.get_accounts();
if (!accounts.length) { if (!accounts.length) {
throw redirect({ throw redirect({
@@ -41,7 +41,7 @@ function Screen() {
try { try {
setLoading(true); setLoading(true);
const loadAccount = await ark.load_selected_account(npub); const loadAccount = await ark.load_account(npub);
if (loadAccount) { if (loadAccount) {
return navigate({ return navigate({
to: "/$account/home", to: "/$account/home",

View File

@@ -11,7 +11,7 @@ export const Route = createFileRoute("/settings/backup")({
component: Screen, component: Screen,
loader: async ({ context }) => { loader: async ({ context }) => {
const ark = context.ark; const ark = context.ark;
const npubs = await ark.get_all_accounts(); const npubs = await ark.get_accounts();
const accounts: Account[] = []; const accounts: Account[] = [];

View File

@@ -29,22 +29,26 @@ export class Ark {
this.settings = undefined; this.settings = undefined;
} }
public async get_all_accounts() { public async get_accounts() {
try { try {
const cmd: string[] = await invoke("get_accounts"); const cmd: string = await invoke("get_accounts");
const accounts: string[] = cmd.map((item) => item.replace(".npub", "")); 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; return accounts;
} catch (e) { } 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 { try {
const cmd: boolean = await invoke("load_selected_account", { const cmd: boolean = await invoke("load_account", {
npub, npub,
}); });
return cmd; return cmd;
@@ -73,7 +77,7 @@ export class Ark {
public async create_keys() { public async create_keys() {
try { try {
const cmd: Keys = await invoke("create_keys"); const cmd: Keys = await invoke("create_account");
return cmd; return cmd;
} catch (e) { } catch (e) {
console.error(String(e)); console.error(String(e));
@@ -82,7 +86,7 @@ export class Ark {
public async save_account(nsec: string, password = "") { public async save_account(nsec: string, password = "") {
try { try {
const cmd: string = await invoke("save_key", { const cmd: string = await invoke("save_account", {
nsec, nsec,
password, password,
}); });

16
src-tauri/Cargo.lock generated
View File

@@ -2668,6 +2668,21 @@ dependencies = [
"windows-sys 0.52.0", "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]] [[package]]
name = "kuchikiki" name = "kuchikiki"
version = "0.8.2" version = "0.8.2"
@@ -2862,6 +2877,7 @@ version = "4.0.0"
dependencies = [ dependencies = [
"cocoa", "cocoa",
"keyring", "keyring",
"keyring-search",
"nostr-sdk", "nostr-sdk",
"objc", "objc",
"rand 0.8.5", "rand 0.8.5",

View File

@@ -33,9 +33,10 @@ tauri-plugin-shell = "2.0.0-beta"
tauri-plugin-updater = "2.0.0-beta" tauri-plugin-updater = "2.0.0-beta"
tauri-plugin-upload = "2.0.0-beta" tauri-plugin-upload = "2.0.0-beta"
tauri-plugin-window-state = "2.0.0-beta" tauri-plugin-window-state = "2.0.0-beta"
tauri-plugin-decorum = "0.1.0"
webpage = { version = "2.0", features = ["serde"] } webpage = { version = "2.0", features = ["serde"] }
keyring = "2" keyring = "2"
tauri-plugin-decorum = "0.1.0" keyring-search = "0.2.0"
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.25.0" cocoa = "0.25.0"

View File

@@ -1,5 +1,4 @@
use std::process::Command; use std::process::Command;
use tauri::Manager;
#[tauri::command] #[tauri::command]
pub async fn show_in_folder(path: String) { 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(); Command::new("open").args(["-R", &path]).spawn().unwrap();
} }
} }
#[tauri::command]
pub fn get_accounts(app_handle: tauri::AppHandle) -> Result<Vec<String>, ()> {
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::<Vec<_>>();
Ok(files)
} else {
Err(())
}
}

View File

@@ -102,12 +102,12 @@ fn main() {
nostr::relay::get_relays, nostr::relay::get_relays,
nostr::relay::connect_relay, nostr::relay::connect_relay,
nostr::relay::remove_relay, nostr::relay::remove_relay,
nostr::keys::create_keys, nostr::keys::get_accounts,
nostr::keys::save_key, nostr::keys::create_account,
nostr::keys::save_account,
nostr::keys::get_encrypted_key, nostr::keys::get_encrypted_key,
nostr::keys::get_stored_nsec,
nostr::keys::nostr_connect, nostr::keys::nostr_connect,
nostr::keys::load_selected_account, nostr::keys::load_account,
nostr::keys::event_to_bech32, nostr::keys::event_to_bech32,
nostr::keys::user_to_bech32, nostr::keys::user_to_bech32,
nostr::keys::to_npub, nostr::keys::to_npub,
@@ -139,7 +139,6 @@ fn main() {
nostr::event::publish, nostr::event::publish,
nostr::event::repost, nostr::event::repost,
commands::folder::show_in_folder, commands::folder::show_in_folder,
commands::folder::get_accounts,
commands::window::create_column, commands::window::create_column,
commands::window::close_column, commands::window::close_column,
commands::window::reposition_column, commands::window::reposition_column,

View File

@@ -1,35 +1,46 @@
use crate::Nostr; use crate::Nostr;
use keyring::Entry; use keyring::Entry;
use keyring_search::{Limit, List, Search};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
use std::{fs::File, str::FromStr}; use tauri::State;
use tauri::{Manager, State};
#[derive(serde::Serialize)] #[derive(serde::Serialize)]
pub struct CreateKeysResponse { pub struct Account {
npub: String, npub: String,
nsec: String, nsec: String,
} }
#[tauri::command] #[tauri::command]
pub fn create_keys() -> Result<CreateKeysResponse, ()> { pub fn get_accounts() -> Result<String, String> {
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<Account, ()> {
let keys = Keys::generate(); let keys = Keys::generate();
let public_key = keys.public_key(); 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 { let result = Account {
npub: public_key.to_bech32().expect("npub failed"), npub: public_key.to_bech32().unwrap(),
nsec: secret_key.to_bech32().expect("nsec failed"), nsec: secret_key.to_bech32().unwrap(),
}; };
Ok(result) Ok(result)
} }
#[tauri::command] #[tauri::command]
pub async fn save_key( pub async fn save_account(
nsec: &str, nsec: &str,
password: &str, password: &str,
app_handle: tauri::AppHandle,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let secret_key: Result<SecretKey, String>; let secret_key: Result<SecretKey, String>;
@@ -38,12 +49,12 @@ pub async fn save_key(
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap(); let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
secret_key = match encrypted_key.to_secret_key(password) { secret_key = match encrypted_key.to_secret_key(password) {
Ok(val) => Ok(val), Ok(val) => Ok(val),
Err(_) => Err("Wrong passphase".into()), Err(err) => Err(err.to_string()),
}; };
} else { } else {
secret_key = match SecretKey::from_bech32(nsec) { secret_key = match SecretKey::from_bech32(nsec) {
Ok(val) => Ok(val), 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 npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap(); let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
let home_dir = app_handle.path().home_dir().unwrap(); let keyring = Entry::new(&npub, "nostr_secret").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.set_password(&nsec); let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(nostr_keys); let signer = NostrSigner::Keys(nostr_keys);
@@ -75,83 +80,29 @@ pub async fn save_key(
} }
#[tauri::command] #[tauri::command]
pub async fn nostr_connect( pub async fn load_account(npub: &str, state: State<'_, Nostr>) -> Result<bool, String> {
npub: &str,
uri: &str,
app_handle: tauri::AppHandle,
state: State<'_, Nostr>,
) -> Result<String, String> {
let client = &state.client; let client = &state.client;
let app_keys = Keys::generate(); let keyring = Entry::new(&npub, "nostr_secret").unwrap();
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<String, String> {
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<String, String> {
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<bool, String> {
let client = &state.client;
let keyring = Entry::new("Lume Secret Storage", npub).unwrap();
match keyring.get_password() { match keyring.get_password() {
Ok(password) => { Ok(password) => {
if password.starts_with("bunker://") { if password.starts_with("bunker://") {
let app_keys = Keys::generate(); let local_keyring = Entry::new(&npub, "bunker_local_account").unwrap();
let bunker_uri = NostrConnectURI::parse(password).unwrap();
let signer = Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(60), None)
.await
.unwrap();
// Update signer match local_keyring.get_password() {
client.set_signer(Some(signer.into())).await; 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 { } else {
let secret_key = SecretKey::from_bech32(password).expect("Get secret key failed"); let secret_key = SecretKey::from_bech32(password).expect("Get secret key failed");
let keys = Keys::new(secret_key); 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<String, String> {
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<String, String> {
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] #[tauri::command]
pub fn event_to_bech32(id: &str, relays: Vec<String>) -> Result<String, ()> { pub fn event_to_bech32(id: &str, relays: Vec<String>) -> Result<String, ()> {
let event_id = EventId::from_hex(id).unwrap(); let event_id = EventId::from_hex(id).unwrap();