wip: nsecbunker

This commit is contained in:
reya 2023-10-20 09:36:49 +07:00
parent e1e54c1a98
commit 7c8d8a09fd
7 changed files with 202 additions and 147 deletions

View File

@ -132,7 +132,7 @@ export function CreateAccountScreen() {
</div> </div>
<div className="mx-auto flex w-full max-w-md flex-col gap-10"> <div className="mx-auto flex w-full max-w-md flex-col gap-10">
<h1 className="text-center text-2xl font-semibold text-neutral-900 dark:text-neutral-100"> <h1 className="text-center text-2xl font-semibold text-neutral-900 dark:text-neutral-100">
Let&apos;s set up your Nostr account. Let&apos;s set up your account.
</h1> </h1>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
{!keys ? ( {!keys ? (

View File

@ -1,3 +1,4 @@
import { NDKNip46Signer, NDKPrivateKeySigner } from '@nostr-dev-kit/ndk';
import { readText } from '@tauri-apps/plugin-clipboard-manager'; import { readText } from '@tauri-apps/plugin-clipboard-manager';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
@ -6,30 +7,52 @@ import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { twMerge } from 'tailwind-merge'; import { twMerge } from 'tailwind-merge';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider'; import { useStorage } from '@libs/storage/provider';
import { ArrowLeftIcon } from '@shared/icons'; import { ArrowLeftIcon } from '@shared/icons';
import { User } from '@shared/user'; import { User } from '@shared/user';
export function ImportAccountScreen() { export function ImportAccountScreen() {
const { db } = useStorage();
const navigate = useNavigate(); const navigate = useNavigate();
const { db } = useStorage();
const { ndk } = useNDK();
const [npub, setNpub] = useState<string>(''); const [npub, setNpub] = useState<string>('');
const [nsec, setNsec] = useState<string>(''); const [nsec, setNsec] = useState<string>('');
const [pubkey, setPubkey] = useState<undefined | string>(undefined); const [pubkey, setPubkey] = useState<undefined | string>(undefined);
const [created, setCreated] = useState(false); const [created, setCreated] = useState({ ok: false, remote: false });
const [savedPrivkey, setSavedPrivkey] = useState(false); const [savedPrivkey, setSavedPrivkey] = useState(false);
const submitNpub = async () => { const submitNpub = async () => {
if (npub.length < 6) return toast('You must enter valid npub'); if (npub.length < 6) return toast.error('You must enter valid npub');
if (!npub.startsWith('npub1')) return toast('npub must be starts with npub1'); if (!npub.startsWith('npub1')) return toast.error('npub must be starts with npub1');
try { try {
const pubkey = nip19.decode(npub).data as string; const pubkey = nip19.decode(npub).data as string;
setPubkey(pubkey); setPubkey(pubkey);
} catch (e) { } catch (e) {
return toast(`npub invalid: ${e}`); return toast.error(`npub invalid: ${e}`);
}
};
const connectNsecBunker = async () => {
if (npub.length < 6) return toast.error('You must enter valid npub');
if (!npub.startsWith('npub1')) return toast.error('npub must be starts with npub1');
try {
const pubkey = nip19.decode(npub.split('#')[0]).data as string;
const localSigner = NDKPrivateKeySigner.generate();
await db.secureSave(pubkey + '-bunker', localSigner.privateKey);
const remoteSigner = new NDKNip46Signer(ndk, npub, localSigner);
ndk.signer = remoteSigner;
setPubkey(pubkey);
setCreated({ ok: false, remote: true });
} catch (e) {
return toast.error(e);
} }
}; };
@ -41,7 +64,9 @@ export function ImportAccountScreen() {
const createAccount = async () => { const createAccount = async () => {
try { try {
await db.createAccount(npub, pubkey); await db.createAccount(npub, pubkey);
setCreated(true); setCreated((prev) => ({ ...prev, ok: true }));
if (created.remote) navigate('/auth/onboarding', { state: { newuser: false } });
} catch (e) { } catch (e) {
return toast(`Create account failed: ${e}`); return toast(`Create account failed: ${e}`);
} }
@ -82,7 +107,7 @@ export function ImportAccountScreen() {
</div> </div>
<div className="mx-auto flex w-full max-w-md flex-col gap-10"> <div className="mx-auto flex w-full max-w-md flex-col gap-10">
<h1 className="text-center text-2xl font-semibold text-neutral-900 dark:text-neutral-100"> <h1 className="text-center text-2xl font-semibold text-neutral-900 dark:text-neutral-100">
Import your Nostr account. Import your account.
</h1> </h1>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<div className="rounded-xl bg-neutral-100 p-3 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200"> <div className="rounded-xl bg-neutral-100 p-3 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200">
@ -90,7 +115,7 @@ export function ImportAccountScreen() {
<label htmlFor="npub" className="font-semibold"> <label htmlFor="npub" className="font-semibold">
Enter your public key: Enter your public key:
</label> </label>
<div className="inline-flex w-full items-center gap-2"> <div className="flex w-full flex-col gap-2">
<input <input
name="npub" name="npub"
type="text" type="text"
@ -101,16 +126,25 @@ export function ImportAccountScreen() {
autoCorrect="off" autoCorrect="off"
autoCapitalize="off" autoCapitalize="off"
placeholder="npub1" placeholder="npub1"
className="h-11 flex-1 rounded-lg bg-neutral-200 px-3 placeholder:text-neutral-500 dark:bg-neutral-800 dark:placeholder:text-neutral-400" className="h-11 w-full rounded-lg bg-neutral-200 px-3 placeholder:text-neutral-500 dark:bg-neutral-800 dark:placeholder:text-neutral-400"
/> />
{!pubkey ? ( {!pubkey ? (
<div className="flex flex-col gap-2">
<button <button
type="button" type="button"
onClick={submitNpub} onClick={submitNpub}
className="h-11 w-24 shrink-0 rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600" className="h-9 w-full shrink-0 rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600"
> >
Continue Continue
</button> </button>
<button
type="button"
onClick={connectNsecBunker}
className="h-9 w-full shrink-0 rounded-lg bg-neutral-200 font-semibold text-neutral-900 hover:bg-neutral-300 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700"
>
Continue with nsecBunker
</button>
</div>
) : null} ) : null}
</div> </div>
</div> </div>
@ -126,32 +160,31 @@ export function ImportAccountScreen() {
> >
<h5 className="mb-1.5 font-semibold">Account found</h5> <h5 className="mb-1.5 font-semibold">Account found</h5>
<div className="flex w-full flex-col gap-2"> <div className="flex w-full flex-col gap-2">
<div className="inline-flex h-full flex-1 items-center rounded-lg bg-neutral-200 p-2"> <div className="flex h-full w-full items-center justify-between rounded-lg bg-neutral-200 p-2">
<User pubkey={pubkey} variant="simple" /> <User pubkey={pubkey} variant="simple" />
</div>
{!created ? (
<div className="flex gap-2">
<button <button
type="button" type="button"
onClick={changeAccount} onClick={changeAccount}
className="h-9 flex-1 shrink-0 rounded-lg bg-neutral-200 font-semibold text-neutral-800 hover:bg-neutral-300 dark:bg-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-700" className="h-8 w-20 shrink-0 rounded-lg bg-neutral-300 text-sm font-medium text-neutral-800 hover:bg-neutral-400 dark:bg-neutral-700 dark:text-neutral-200 dark:hover:bg-neutral-600"
> >
Change account Change
</button> </button>
</div>
{!created.ok ? (
<button <button
type="button" type="button"
onClick={createAccount} onClick={createAccount}
className="h-9 flex-1 shrink-0 rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600" className="h-9 w-full shrink-0 rounded-lg bg-blue-500 font-semibold text-white hover:bg-blue-600"
> >
Continue Continue
</button> </button>
</div>
) : null} ) : null}
</div> </div>
</motion.div> </motion.div>
) : null} ) : null}
{created ? ( {created.ok ? (
<> <>
{!created.remote ? (
<motion.div <motion.div
initial={{ opacity: 0, y: 50 }} initial={{ opacity: 0, y: 50 }}
animate={{ animate={{
@ -209,8 +242,8 @@ export function ImportAccountScreen() {
<div className="mt-3 select-text"> <div className="mt-3 select-text">
<p className="text-sm"> <p className="text-sm">
<b>Private Key</b> is used to sign your event. For example, if you <b>Private Key</b> is used to sign your event. For example, if you
want to make a new post or send a message to your contact, you need to want to make a new post or send a message to your contact, you need
use your private key to sign this event. to use your private key to sign this event.
</p> </p>
<h5 className="mt-2 font-semibold"> <h5 className="mt-2 font-semibold">
1. In case you store private key in Lume 1. In case you store private key in Lume
@ -230,12 +263,13 @@ export function ImportAccountScreen() {
2. In case you do not store private key in Lume 2. In case you do not store private key in Lume
</h5> </h5>
<p className="text-sm"> <p className="text-sm">
When you make an event that requires a sign by your private key, Lume When you make an event that requires a sign by your private key,
will show a prompt for you to enter private key. It will be cleared Lume will show a prompt for you to enter private key. It will be
after signing and not stored anywhere. cleared after signing and not stored anywhere.
</p> </p>
</div> </div>
</motion.div> </motion.div>
) : null}
<motion.button <motion.button
initial={{ opacity: 0, y: 80 }} initial={{ opacity: 0, y: 80 }}
animate={{ animate={{
@ -248,7 +282,7 @@ export function ImportAccountScreen() {
navigate('/auth/onboarding', { state: { newuser: false } }) navigate('/auth/onboarding', { state: { newuser: false } })
} }
> >
Finish Continue
</motion.button> </motion.button>
</> </>
) : null} ) : null}

View File

@ -15,13 +15,13 @@ export function WelcomeScreen() {
to="/auth/create" to="/auth/create"
className="inline-flex h-10 w-full items-center justify-center rounded-lg bg-blue-500 font-medium text-white hover:bg-blue-600" className="inline-flex h-10 w-full items-center justify-center rounded-lg bg-blue-500 font-medium text-white hover:bg-blue-600"
> >
Create new Nostr account Create new account
</Link> </Link>
<Link <Link
to="/auth/import" to="/auth/import"
className="inline-flex h-10 w-full items-center justify-center rounded-lg font-medium text-neutral-900 hover:bg-neutral-100 dark:text-neutral-100 dark:hover:bg-neutral-900" className="inline-flex h-10 w-full items-center justify-center rounded-lg font-medium text-neutral-900 hover:bg-neutral-100 dark:text-neutral-100 dark:hover:bg-neutral-900"
> >
Log in with key Log in
</Link> </Link>
</div> </div>
</div> </div>

View File

@ -1,4 +1,4 @@
import NDK from '@nostr-dev-kit/ndk'; import NDK, { NDKNip46Signer, NDKPrivateKeySigner } from '@nostr-dev-kit/ndk';
import NDKCacheAdapterDexie from '@nostr-dev-kit/ndk-cache-dexie'; import NDKCacheAdapterDexie from '@nostr-dev-kit/ndk-cache-dexie';
import { ndkAdapter } from '@nostr-fetch/adapter-ndk'; import { ndkAdapter } from '@nostr-fetch/adapter-ndk';
import { message } from '@tauri-apps/plugin-dialog'; import { message } from '@tauri-apps/plugin-dialog';
@ -52,9 +52,30 @@ export const NDKInstance = () => {
} }
} }
async function getSigner(instance: NDK) {
if (!db.account) return null;
// NIP-46 Signer
const localSignerPrivkey = await db.secureLoad(db.account.pubkey + '-bunker');
if (localSignerPrivkey) {
const localSigner = new NDKPrivateKeySigner(localSignerPrivkey);
const remoteSigner = new NDKNip46Signer(instance, db.account.id, localSigner);
// await remoteSigner.blockUntilReady();
return remoteSigner;
}
// Privkey Signer
const userPrivkey = await db.secureLoad(db.account.pubkey);
if (userPrivkey) return new NDKPrivateKeySigner(userPrivkey);
return null;
}
async function initNDK() { async function initNDK() {
const explicitRelayUrls = await getExplicitRelays();
const outboxSetting = await db.getSettingValue('outbox'); const outboxSetting = await db.getSettingValue('outbox');
const explicitRelayUrls = await getExplicitRelays();
const dexieAdapter = new NDKCacheAdapterDexie({ dbName: 'lume_ndkcache' }); const dexieAdapter = new NDKCacheAdapterDexie({ dbName: 'lume_ndkcache' });
const instance = new NDK({ const instance = new NDK({
explicitRelayUrls, explicitRelayUrls,
@ -64,7 +85,11 @@ export const NDKInstance = () => {
}); });
try { try {
await instance.connect(); // connect
await instance.connect(2000);
// add signer
const signer = await getSigner(instance);
instance.signer = signer;
} catch (error) { } catch (error) {
await message(`NDK instance init failed: ${error}`, { await message(`NDK instance init failed: ${error}`, {
title: 'Lume', title: 'Lume',

View File

@ -1,3 +1,4 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { message } from '@tauri-apps/plugin-dialog'; import { message } from '@tauri-apps/plugin-dialog';
import Image from '@tiptap/extension-image'; import Image from '@tiptap/extension-image';
import Placeholder from '@tiptap/extension-placeholder'; import Placeholder from '@tiptap/extension-placeholder';
@ -7,20 +8,19 @@ import { convert } from 'html-to-text';
import { useState } from 'react'; import { useState } from 'react';
import { twMerge } from 'tailwind-merge'; import { twMerge } from 'tailwind-merge';
import { useNDK } from '@libs/ndk/provider';
import { MediaUploader, MentionPopup } from '@shared/composer'; import { MediaUploader, MentionPopup } from '@shared/composer';
import { CancelIcon, LoaderIcon } from '@shared/icons'; import { CancelIcon, LoaderIcon } from '@shared/icons';
import { MentionNote } from '@shared/notes'; import { MentionNote } from '@shared/notes';
import { useComposer } from '@stores/composer'; import { useComposer } from '@stores/composer';
import { useNostr } from '@utils/hooks/useNostr';
import { sendNativeNotification } from '@utils/notification';
export function Composer() { export function Composer() {
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
const [reply, clearReply] = useComposer((state) => [state.reply, state.clearReply]); const [reply, clearReply] = useComposer((state) => [state.reply, state.clearReply]);
const { publish } = useNostr(); const { ndk } = useNDK();
const expand = useComposer((state) => state.expand); const expand = useComposer((state) => state.expand);
const editor = useEditor({ const editor = useEditor({
@ -92,11 +92,13 @@ export function Composer() {
}); });
// publish message // publish message
await publish({ content: serializedContent, kind: 1, tags }); const event = new NDKEvent(ndk);
event.content = serializedContent;
// send native notifiation event.kind = NDKKind.Text;
await sendNativeNotification('Post has been published successfully.'); event.tags = tags;
const publish = event.publish();
if (publish) {
// update state // update state
setLoading(false); setLoading(false);
// reset editor // reset editor
@ -105,6 +107,7 @@ export function Composer() {
if (reply.id) { if (reply.id) {
clearReply(); clearReply();
} }
}
} catch { } catch {
setLoading(false); setLoading(false);
await message('Publishing post failed.', { title: 'Lume', type: 'error' }); await message('Publishing post failed.', { title: 'Lume', type: 'error' });

View File

@ -304,20 +304,14 @@ export function useNostr() {
kind: NDKKind | number; kind: NDKKind | number;
tags: string[][]; tags: string[][];
}): Promise<NDKEvent> => { }): Promise<NDKEvent> => {
const privkey: string = await db.secureLoad(db.account.pubkey);
// #TODO: show prompt
if (!privkey) return;
const event = new NDKEvent(ndk); const event = new NDKEvent(ndk);
const signer = new NDKPrivateKeySigner(privkey);
event.content = content; event.content = content;
event.kind = kind; event.kind = kind;
event.created_at = Math.floor(Date.now() / 1000); event.created_at = Math.floor(Date.now() / 1000);
event.pubkey = db.account.pubkey; event.pubkey = db.account.pubkey;
event.tags = tags; event.tags = tags;
await event.sign(signer); await event.sign();
await event.publish(); await event.publish();
return event; return event;

View File

@ -22,8 +22,7 @@ export interface DBEvent {
} }
export interface Account extends NDKUserProfile { export interface Account extends NDKUserProfile {
id: number; id: string;
npub: string;
pubkey: string; pubkey: string;
follows: null | string[]; follows: null | string[];
circles: null | string[]; circles: null | string[];