feat: always use ncryptsec

This commit is contained in:
reya
2024-08-04 18:37:47 +07:00
parent 668238656e
commit f1b131db0a
9 changed files with 155 additions and 115 deletions

View File

@@ -17,7 +17,7 @@ pub struct EventPayload {
#[specta::specta] #[specta::specta]
pub fn get_accounts() -> Vec<String> { pub fn get_accounts() -> Vec<String> {
let search = Search::new().expect("Unexpected."); let search = Search::new().expect("Unexpected.");
let results = search.by_service("coop"); let results = search.by_service("Coop Secret Storage");
let list = List::list_credentials(&results, Limit::All); let list = List::list_credentials(&results, Limit::All);
let accounts: HashSet<String> = let accounts: HashSet<String> =
list.split_whitespace().filter(|v| v.starts_with("npub1")).map(String::from).collect(); list.split_whitespace().filter(|v| v.starts_with("npub1")).map(String::from).collect();
@@ -48,7 +48,7 @@ pub async fn get_metadata(id: String, state: State<'_, Nostr>) -> Result<String,
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn delete_account(id: String) -> Result<(), String> { pub fn delete_account(id: String) -> Result<(), String> {
let keyring = Entry::new("coop", &id).map_err(|e| e.to_string())?; let keyring = Entry::new("Coop Secret Storage", &id).map_err(|e| e.to_string())?;
let _ = keyring.delete_credential(); let _ = keyring.delete_credential();
Ok(()) Ok(())
@@ -67,7 +67,7 @@ pub async fn create_account(
let nsec = keys.secret_key().unwrap().to_bech32().map_err(|e| e.to_string())?; let nsec = keys.secret_key().unwrap().to_bech32().map_err(|e| e.to_string())?;
// Save account // Save account
let keyring = Entry::new("coop", &npub).unwrap(); let keyring = Entry::new("Coop Secret Storage", &npub).unwrap();
let _ = keyring.set_password(&nsec); let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(keys); let signer = NostrSigner::Keys(keys);
@@ -95,36 +95,34 @@ pub async fn create_account(
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn import_key( pub async fn import_key(
nsec: &str, key: String,
password: &str, password: Option<String>,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let secret_key = if nsec.starts_with("ncryptsec") { let client = &state.client;
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap(); let secret_key = SecretKey::from_bech32(key).map_err(|err| err.to_string())?;
encrypted_key.to_secret_key(password).map_err(|err| err.to_string()) let keys = Keys::new(secret_key.clone());
} else { let npub = keys.public_key().to_bech32().unwrap();
SecretKey::from_bech32(nsec).map_err(|err| err.to_string())
let enc_bech32 = match password {
Some(pw) => {
let enc = EncryptedSecretKey::new(&secret_key, pw, 16, KeySecurity::Medium)
.map_err(|err| err.to_string())?;
enc.to_bech32().map_err(|err| err.to_string())?
}
None => secret_key.to_bech32().map_err(|err| err.to_string())?,
}; };
match secret_key { let keyring = Entry::new("Coop Secret Storage", &npub).unwrap();
Ok(val) => { let _ = keyring.set_password(&enc_bech32);
let nostr_keys = Keys::new(val);
let npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
let keyring = Entry::new("coop", &npub).unwrap(); let signer = NostrSigner::Keys(keys);
let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(nostr_keys); // Update client's signer
let client = &state.client; client.set_signer(Some(signer)).await;
// Update client's signer Ok(npub)
client.set_signer(Some(signer)).await;
Ok(npub)
}
Err(msg) => Err(msg),
}
} }
#[tauri::command] #[tauri::command]
@@ -143,7 +141,7 @@ pub async fn connect_account(uri: &str, state: State<'_, Nostr>) -> Result<Strin
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await { match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await {
Ok(signer) => { Ok(signer) => {
let keyring = Entry::new("coop", &remote_npub).unwrap(); let keyring = Entry::new("Coop Secret Storage", &remote_npub).unwrap();
let _ = keyring.set_password(&app_secret); let _ = keyring.set_password(&app_secret);
// Update signer // Update signer
@@ -220,21 +218,23 @@ pub async fn set_inbox(relays: Vec<String>, state: State<'_, Nostr>) -> Result<(
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn login( pub async fn login(
id: String, account: String,
password: String,
state: State<'_, Nostr>, state: State<'_, Nostr>,
handle: tauri::AppHandle, handle: tauri::AppHandle,
) -> Result<String, String> { ) -> Result<String, String> {
let client = &state.client; let client = &state.client;
let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?; let keyring = Entry::new("Coop Secret Storage", &account).map_err(|e| e.to_string())?;
let hex = public_key.to_hex();
let keyring = Entry::new("coop", &id).map_err(|e| e.to_string())?;
let password = match keyring.get_password() { let bech32 = match keyring.get_password() {
Ok(pw) => pw, Ok(pw) => pw,
Err(_) => return Err("Cancelled".into()), Err(_) => return Err("Action have been cancelled".into()),
}; };
let keys = Keys::parse(password).map_err(|e| e.to_string())?; let ncryptsec = EncryptedSecretKey::from_bech32(bech32).map_err(|e| e.to_string())?;
let secret_key = ncryptsec.to_secret_key(password).map_err(|e| e.to_string())?;
let keys = Keys::new(secret_key);
let public_key = keys.public_key();
let signer = NostrSigner::Keys(keys); let signer = NostrSigner::Keys(keys);
// Update signer // Update signer
@@ -363,5 +363,5 @@ pub async fn login(
.await .await
}); });
Ok(hex) Ok(public_key.to_hex())
} }

View File

@@ -15,7 +15,7 @@ pub async fn get_chats(state: State<'_, Nostr>) -> Result<Vec<String>, String> {
let filter = Filter::new().kind(Kind::PrivateDirectMessage).pubkey(public_key); let filter = Filter::new().kind(Kind::PrivateDirectMessage).pubkey(public_key);
match client.database().query(vec![filter.clone()], Order::Desc).await { match client.database().query(vec![filter], Order::Asc).await {
Ok(events) => { Ok(events) => {
let ev = events let ev = events
.into_iter() .into_iter()
@@ -38,7 +38,7 @@ pub async fn get_chat_messages(id: String, state: State<'_, Nostr>) -> Result<Ve
let signer = client.signer().await.map_err(|e| e.to_string())?; let signer = client.signer().await.map_err(|e| e.to_string())?;
let receiver = signer.public_key().await.map_err(|e| e.to_string())?; let receiver = signer.public_key().await.map_err(|e| e.to_string())?;
let sender = PublicKey::parse(id.clone()).map_err(|e| e.to_string())?; let sender = PublicKey::parse(id).map_err(|e| e.to_string())?;
let recv_filter = let recv_filter =
Filter::new().kind(Kind::PrivateDirectMessage).author(sender).pubkey(receiver); Filter::new().kind(Kind::PrivateDirectMessage).author(sender).pubkey(receiver);

View File

@@ -4,9 +4,9 @@
/** user-defined commands **/ /** user-defined commands **/
export const commands = { export const commands = {
async login(id: string) : Promise<Result<string, string>> { async login(account: string, password: string) : Promise<Result<string, string>> {
try { try {
return { status: "ok", data: await TAURI_INVOKE("login", { id }) }; return { status: "ok", data: await TAURI_INVOKE("login", { account, password }) };
} catch (e) { } catch (e) {
if(e instanceof Error) throw e; if(e instanceof Error) throw e;
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
@@ -28,9 +28,9 @@ try {
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
} }
}, },
async importKey(nsec: string, password: string) : Promise<Result<string, string>> { async importKey(key: string, password: string | null) : Promise<Result<string, string>> {
try { try {
return { status: "ok", data: await TAURI_INVOKE("import_key", { nsec, password }) }; return { status: "ok", data: await TAURI_INVOKE("import_key", { key, password }) };
} catch (e) { } catch (e) {
if(e instanceof Error) throw e; if(e instanceof Error) throw e;
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };

View File

@@ -291,7 +291,7 @@ function List() {
function Form() { function Form() {
const { id } = Route.useParams(); const { id } = Route.useParams();
const { inbox } = Route.useRouteContext(); const inboxRelays = Route.useLoaderData();
const [newMessage, setNewMessage] = useState(""); const [newMessage, setNewMessage] = useState("");
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
@@ -313,7 +313,7 @@ function Form() {
return ( return (
<div className="h-12 shrink-0 flex items-center justify-center px-3.5"> <div className="h-12 shrink-0 flex items-center justify-center px-3.5">
{!inbox.length ? ( {!inboxRelays.length ? (
<div className="text-xs"> <div className="text-xs">
This user doesn't have inbox relays. You cannot send messages to them. This user doesn't have inbox relays. You cannot send messages to them.
</div> </div>

View File

@@ -2,8 +2,10 @@ import { createFileRoute } from "@tanstack/react-router";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
export const Route = createFileRoute("/$account/chats/$id")({ export const Route = createFileRoute("/$account/chats/$id")({
beforeLoad: async ({ params }) => { loader: async ({ params }) => {
const inbox: string[] = await invoke("connect_inbox", { id: params.id }); const inboxRelays: string[] = await invoke("connect_inbox", {
return { inbox }; id: params.id,
});
return inboxRelays;
}, },
}); });

View File

@@ -17,6 +17,7 @@ import { Link, Outlet, createLazyFileRoute } from "@tanstack/react-router";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu"; import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu";
import { message } from "@tauri-apps/plugin-dialog"; import { message } from "@tauri-apps/plugin-dialog";
import { open } from "@tauri-apps/plugin-shell";
import type { NostrEvent } from "nostr-tools"; import type { NostrEvent } from "nostr-tools";
import { useCallback, useEffect, useState, useTransition } from "react"; import { useCallback, useEffect, useState, useTransition } from "react";
@@ -362,8 +363,8 @@ function Compose() {
> >
<User.Provider pubkey={contact}> <User.Provider pubkey={contact}>
<User.Root className="flex items-center gap-2"> <User.Root className="flex items-center gap-2">
<User.Avatar className="size-10 rounded-full" /> <User.Avatar className="size-8 rounded-full" />
<User.Name className="font-medium" /> <User.Name className="text-sm font-medium" />
</User.Root> </User.Root>
</User.Provider> </User.Provider>
</button> </button>
@@ -406,7 +407,7 @@ function CurrentUser() {
}), }),
MenuItem.new({ MenuItem.new({
text: "Feedback", text: "Feedback",
action: () => navigate({ to: "/" }), action: async () => await open("https://github.com/lumehq/coop/issues"),
}), }),
PredefinedMenuItem.new({ item: "Separator" }), PredefinedMenuItem.new({ item: "Separator" }),
MenuItem.new({ MenuItem.new({

View File

@@ -25,14 +25,22 @@ function Screen() {
const submit = async () => { const submit = async () => {
startTransition(async () => { startTransition(async () => {
if (!key.startsWith("nsec1")) { if (!key.startsWith("nsec1") && !key.startsWith("ncryptsec")) {
await message( await message(
"You need to enter a valid private key starts with nsec or ncryptsec", "You need to enter a valid private key starts with nsec or ncryptsec",
{ title: "Import Key", kind: "info" }, { title: "Login", kind: "info" },
); );
return; return;
} }
if (key.startsWith("nsec1") && !password.length) {
await message("You must set password to secure your key", {
title: "Login",
kind: "info",
});
return;
}
const res = await commands.importKey(key, password); const res = await commands.importKey(key, password);
if (res.status === "ok") { if (res.status === "ok") {
@@ -63,47 +71,48 @@ function Screen() {
className="flex flex-col gap-3 p-3 rounded-xl overflow-hidden" className="flex flex-col gap-3 p-3 rounded-xl overflow-hidden"
shadow shadow
> >
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1.5">
<label <label
htmlFor="key" htmlFor="key"
className="font-medium text-neutral-900 dark:text-neutral-100" className="text-sm font-medium text-neutral-800 dark:text-neutral-200"
> >
Private Key Private Key
</label> </label>
<div className="relative"> <div className="relative">
<input <input
name="key" name="key"
type="text" type="password"
placeholder="nsec or ncryptsec..." placeholder="nsec or ncryptsec..."
value={key} value={key}
onChange={(e) => setKey(e.target.value)} onChange={(e) => setKey(e.target.value)}
className="pl-3 pr-12 rounded-lg w-full h-10 bg-transparent border border-neutral-200 dark:border-neutral-500 focus:border-blue-500 focus:outline-none" className="pl-3 pr-12 rounded-lg w-full h-10 bg-transparent border border-neutral-200 dark:border-neutral-500 focus:border-blue-500 focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/> />
<button <button
type="button" type="button"
onClick={() => pasteFromClipboard()} onClick={() => pasteFromClipboard()}
className="absolute top-1/2 right-2 transform -translate-y-1/2 text-xs font-semibold text-blue-500" className="absolute uppercase top-1/2 right-2 transform -translate-y-1/2 text-xs font-semibold text-blue-500"
> >
Paste Paste
</button> </button>
</div> </div>
</div> </div>
<div className="flex flex-col gap-1"> {key.length && !key.startsWith("ncryptsec") ? (
<label <div className="flex flex-col gap-1">
htmlFor="password" <label
className="font-medium text-neutral-900 dark:text-neutral-100" htmlFor="password"
> className="text-sm font-medium text-neutral-800 dark:text-neutral-200"
Password (Optional) >
</label> Set password to secure your key
<input </label>
name="password" <input
type="password" name="password"
value={password} type="password"
onChange={(e) => setPassword(e.target.value)} value={password}
className="px-3 rounded-lg h-10 bg-transparent border border-neutral-200 dark:border-neutral-500 focus:border-blue-500 focus:outline-none" onChange={(e) => setPassword(e.target.value)}
/> className="px-3 rounded-lg h-10 bg-transparent border border-neutral-200 dark:border-neutral-500 focus:border-blue-500 focus:outline-none"
</div> />
</div>
) : null}
</Frame> </Frame>
<div className="flex flex-col items-center gap-1"> <div className="flex flex-col items-center gap-1">
<button <button

View File

@@ -3,8 +3,9 @@ import { npub } from "@/commons";
import { Frame } from "@/components/frame"; import { Frame } from "@/components/frame";
import { Spinner } from "@/components/spinner"; import { Spinner } from "@/components/spinner";
import { User } from "@/components/user"; import { User } from "@/components/user";
import { Plus, X } from "@phosphor-icons/react"; import { ArrowRight, Plus, X } from "@phosphor-icons/react";
import { Link, createLazyFileRoute } from "@tanstack/react-router"; import { Link, createLazyFileRoute } from "@tanstack/react-router";
import { message } from "@tauri-apps/plugin-dialog";
import { useEffect, useMemo, useState, useTransition } from "react"; import { useEffect, useMemo, useState, useTransition } from "react";
export const Route = createLazyFileRoute("/")({ export const Route = createLazyFileRoute("/")({
@@ -27,6 +28,7 @@ function Screen() {
const [accounts, setAccounts] = useState([]); const [accounts, setAccounts] = useState([]);
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const [password, setPassword] = useState("");
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
const deleteAccount = async (npub: string) => { const deleteAccount = async (npub: string) => {
@@ -37,10 +39,15 @@ function Screen() {
} }
}; };
const loginWith = async (npub: string) => { const selectAccount = (account: string) => {
setValue(npub); setValue(account);
};
const loginWith = async () => {
startTransition(async () => { startTransition(async () => {
const res = await commands.login(npub); if (!value || !password) return;
const res = await commands.login(value, password);
if (res.status === "ok") { if (res.status === "ok") {
navigate({ navigate({
@@ -52,9 +59,11 @@ function Screen() {
if (res.error === "404") { if (res.error === "404") {
navigate({ navigate({
to: "/$account/relays", to: "/$account/relays",
params: { account: npub }, params: { account: value },
replace: true, replace: true,
}); });
} else {
await message(res.error, { title: "Login", kind: "error" });
} }
} }
}); });
@@ -83,33 +92,51 @@ function Screen() {
{accounts.map((account) => ( {accounts.map((account) => (
<div <div
key={account} key={account}
onClick={() => loginWith(account)} onClick={() => selectAccount(account)}
onKeyDown={() => loginWith(account)} onKeyDown={() => selectAccount(account)}
className="group flex items-center justify-between hover:bg-black/5 dark:hover:bg-white/5" className="group flex items-center gap-2 hover:bg-black/5 dark:hover:bg-white/5 p-3"
> >
<User.Provider pubkey={account}> <User.Provider pubkey={account}>
<User.Root className="flex items-center gap-2.5 p-3"> <User.Root className="flex-1 flex items-center gap-2.5">
<User.Avatar className="rounded-full size-10" /> <User.Avatar className="rounded-full size-10" />
<div className="inline-flex flex-col items-start"> {value === account ? (
<User.Name className="max-w-[6rem] truncate font-medium leading-tight" /> <div className="flex-1 flex items-center gap-2">
<span className="text-sm text-neutral-700 dark:text-neutral-300"> <input
{npub(account, 16)} name="password"
</span> type="password"
</div> value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") loginWith();
}}
placeholder="Password"
className="px-3 rounded-full w-full h-10 bg-transparent border border-neutral-200 dark:border-neutral-500 focus:border-blue-500 focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
</div>
) : (
<div className="inline-flex flex-col items-start">
<User.Name className="max-w-[6rem] truncate font-medium leading-tight" />
<span className="text-sm text-neutral-700 dark:text-neutral-300">
{npub(account, 16)}
</span>
</div>
)}
</User.Root> </User.Root>
</User.Provider> </User.Provider>
<div className="inline-flex items-center justify-center size-10"> <div className="inline-flex items-center justify-center size-8 shrink-0">
{value === account && isPending ? ( {value === account ? (
<Spinner /> isPending ? (
) : ( <Spinner className="size-4" />
<button ) : (
type="button" <button
onClick={() => deleteAccount(account)} type="button"
className="size-10 hidden group-hover:flex items-center justify-center text-neutral-600 dark:text-neutral-400" onClick={() => loginWith()}
> className="rounded-full size-10 inline-flex items-center justify-center"
<X className="size-4" /> >
</button> <ArrowRight className="size-4" />
)} </button>
)
) : null}
</div> </div>
</div> </div>
))} ))}

View File

@@ -16,27 +16,28 @@ function Screen() {
Direct Message on Nostr. Direct Message on Nostr.
</h1> </h1>
</div> </div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-4">
<Link <Link
to="/create-account" to="/create-account"
className="w-full h-10 bg-blue-500 hover:bg-blue-600 text-white rounded-lg inline-flex items-center justify-center shadow" className="w-full h-10 bg-blue-500 font-medium hover:bg-blue-600 text-white rounded-lg inline-flex items-center justify-center shadow"
> >
Create a new identity Create a new identity
</Link> </Link>
<Link <div className="w-full h-px bg-black/5 dark:bg-white/5" />
to="/import-key" <div className="flex flex-col gap-2">
className="w-full h-10 bg-white hover:bg-neutral-100 dark:hover:bg-neutral-100 dark:bg-white dark:text-black rounded-lg inline-flex items-center justify-center" {/*<Link
> to="/import-key"
Login with Private Key className="w-full h-10 bg-white hover:bg-neutral-100 dark:hover:bg-neutral-100 dark:bg-white dark:text-black rounded-lg inline-flex items-center justify-center"
</Link> >
{/* Login with Nostr Connect
<Link </Link>*/}
to="/import-key" <Link
className="w-full text-sm text-neutral-600 dark:text-neutral-400 inline-flex items-center justify-center" to="/import-key"
> className="w-full h-10 bg-white hover:bg-neutral-100 dark:hover:bg-neutral-100 dark:bg-white dark:text-black rounded-lg inline-flex items-center justify-center"
Login with Private Key (not recommended) >
</Link> Login with Private Key
*/} </Link>
</div>
</div> </div>
</div> </div>
</div> </div>