diff --git a/.agents/skills/onchain-bitcoin/SKILL.md b/.agents/skills/onchain-bitcoin/SKILL.md index 94d780a..e1e1472 100644 --- a/.agents/skills/onchain-bitcoin/SKILL.md +++ b/.agents/skills/onchain-bitcoin/SKILL.md @@ -133,7 +133,7 @@ export function useCurrentUser() { ); } case 'extension': - return new NUser(login.type, login.pubkey, new NBrowserSignerBtc()); + return new NUser(login.type, login.pubkey, new NBrowserSignerBtc({ pubkey: login.pubkey })); default: throw new Error(`Unsupported login type: ${login.type}`); } diff --git a/.agents/skills/onchain-bitcoin/files/lib/bitcoin-signers.ts b/.agents/skills/onchain-bitcoin/files/lib/bitcoin-signers.ts index 0e8b732..cf01611 100644 --- a/.agents/skills/onchain-bitcoin/files/lib/bitcoin-signers.ts +++ b/.agents/skills/onchain-bitcoin/files/lib/bitcoin-signers.ts @@ -1,8 +1,9 @@ import type { NostrSigner } from '@nostrify/types'; -import { NSecSigner, NBrowserSigner, NConnectSigner } from '@nostrify/nostrify'; +import { NSecSigner, NConnectSigner } from '@nostrify/nostrify'; import type { NConnectSignerOpts } from '@nostrify/nostrify'; import { signPsbtLocal } from '@/lib/bitcoin'; +import { Nip07Signer } from '@/lib/Nip07Signer'; // --------------------------------------------------------------------------- // BtcSigner interface @@ -56,28 +57,28 @@ export class NSecSignerBtc extends NSecSigner implements BtcSigner { // --------------------------------------------------------------------------- /** - * Extends `NBrowserSigner` with NIP-07 `window.nostr.signPsbt()` support. + * Extends the template's `Nip07Signer` with NIP-07 `window.nostr.signPsbt()` + * support. Like `Nip07Signer`, it acts as the login's account (`pubkey`) + * through the extension's `getSigner` where the extension offers it. * * Calls the extension's `signPsbt` method if available. If the extension does * not expose `signPsbt`, an error is thrown with a user-friendly message. */ -export class NBrowserSignerBtc extends NBrowserSigner implements BtcSigner { - constructor(opts?: { timeout?: number }) { +export class NBrowserSignerBtc extends Nip07Signer implements BtcSigner { + constructor(opts?: { pubkey?: string; timeout?: number }) { super(opts); } async signPsbt(psbtHex: string): Promise { - // `awaitNostr` is TypeScript-private but JavaScript-public at runtime. - const nostr = await (this as unknown as { awaitNostr(): Promise> }).awaitNostr(); + const signer = await this.signer(); - if (typeof nostr.signPsbt !== 'function') { + if (typeof signer.signPsbt !== 'function') { throw new Error( "Your browser extension doesn't support sending Bitcoin. Try a different extension, or log in with your secret key.", ); } - const signPsbt = nostr.signPsbt as (hex: string) => Promise; - return signPsbt(psbtHex); + return signer.signPsbt(psbtHex); } } diff --git a/README.md b/README.md index 97c1130..f60d332 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ A fresh copy fails lint until it's made into a real app. The rules check for thi ## What's included - **Login:** `LoginArea` opens a dialog for signing up, a browser extension (NIP-07), a private key or a remote signer (NIP-46), and becomes an account switcher once logged in. + Extension logins use the optional `window.nostr.connect`, `getSigner` and `disconnect` where the extension offers them (Din and Tenna do), so the app keeps signing as each login's own account when the user switches accounts in the extension. - **Hooks:** `useCurrentUser`, `useAuthor`, `useNostrPublish`, `useUploadFile` (Blossom), `useLoggedInAccounts`, `useTheme`, `useIsMobile` and others in `src/hooks/`. - **Relays:** a default relay pool, and the user's NIP-65 relay list loaded on login and published when it changes. - **NIP-19 routing:** `npub`, `nprofile`, `note`, `nevent` and `naddr` identifiers are routed at the URL root to `src/pages/NIP19Page.tsx`. diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 1a03c1e..6a4ff2e 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -5,6 +5,7 @@ import { NostrContext } from '@nostrify/react'; import { NUser, useNostrLogin } from '@nostrify/react/login'; import { useQueryClient } from '@tanstack/react-query'; import { useAppContext } from '@/hooks/useAppContext'; +import { Nip07Signer } from '@/lib/Nip07Signer'; interface NostrProviderProps { children: React.ReactNode; @@ -106,7 +107,8 @@ const NostrProvider: React.FC = (props) => { case 'bunker': return NUser.fromBunkerLogin(currentLogin, pool).signer; case 'extension': - return NUser.fromExtensionLogin(currentLogin).signer; + // Pinned to the login's account where the extension offers getSigner. + return new Nip07Signer({ pubkey: currentLogin.pubkey }); default: return undefined; } diff --git a/src/components/NostrSync.tsx b/src/components/NostrSync.tsx index d9bbefd..592b240 100644 --- a/src/components/NostrSync.tsx +++ b/src/components/NostrSync.tsx @@ -1,8 +1,10 @@ -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useNostr } from '@nostrify/react'; +import { useNostrLogin } from '@nostrify/react/login'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAppContext } from '@/hooks/useAppContext'; import { parseBlossomServerList } from '@/lib/appBlossom'; +import { getNip07Provider, hasDisconnect } from '@/lib/nip07'; /** * NostrSync - Syncs user's Nostr data @@ -11,11 +13,31 @@ import { parseBlossomServerList } from '@/lib/appBlossom'; * Currently syncs: * - NIP-65 relay list (kind 10002) * - BUD-03 Blossom server list (kind 10063) + * + * It also gives an extension login's account back to the extension when it + * logs out, where the extension can take it (`window.nostr.disconnect`, as + * Din and Tenna offer), so the site no longer holds it there either. */ export function NostrSync() { const { nostr } = useNostr(); const { user } = useCurrentUser(); const { config, updateConfig } = useAppContext(); + const { logins } = useNostrLogin(); + const extensionLogins = useRef>(new Set()); + + useEffect(() => { + const current = new Set( + logins.filter((login) => login.type === 'extension').map((login) => login.pubkey), + ); + const provider = getNip07Provider(); + for (const pubkey of extensionLogins.current) { + if (current.has(pubkey) || !hasDisconnect(provider)) continue; + provider.disconnect(pubkey).catch((error: unknown) => { + console.warn("The extension didn't take the account back:", error); + }); + } + extensionLogins.current = current; + }, [logins]); useEffect(() => { if (!user) return; diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index 00f0bd8..0f3589d 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -3,26 +3,11 @@ import { Button } from '@/components/ui/button.tsx'; import AuthDialog from './AuthDialog'; import { QuickLoginDialog } from './QuickLoginDialog'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; +import { useLoginActions } from '@/hooks/useLoginActions'; +import { getNip07Provider, hasConnect } from '@/lib/nip07'; import { AccountSwitcher } from './AccountSwitcher'; import { cn } from '@/lib/utils'; -/** Minimal shape of the NIP-07 provider injected at `window.nostr`. */ -interface Nip07Provider { - getPublicKey(): Promise; -} - -function getNip07Provider(): Nip07Provider | undefined { - if (typeof window === 'undefined' || !('nostr' in window)) return undefined; - const provider = (window as { nostr?: unknown }).nostr; - if ( - provider && - typeof (provider as Nip07Provider).getPublicKey === 'function' - ) { - return provider as Nip07Provider; - } - return undefined; -} - export interface LoginAreaProps { className?: string; } @@ -31,10 +16,22 @@ export function LoginArea({ className }: LoginAreaProps) { const { currentUser } = useLoggedInAccounts(); const [authDialogOpen, setAuthDialogOpen] = useState(false); const [quickLoginPubkey, setQuickLoginPubkey] = useState(null); + const login = useLoginActions(); + // An extension that can give the site an account (connect) is asked for one + // straight away, since it shows the account itself. Otherwise one that + // exposes a pubkey gets the one-tap "Welcome back" dialog. Either way a + // refusal falls through to the full dialog. const handleJoin = async () => { const provider = getNip07Provider(); - if (provider) { + if (hasConnect(provider)) { + try { + await login.extension(); + return; + } catch { + // Declined or errored — fall through to the full dialog. + } + } else if (provider) { try { const pubkey = await provider.getPublicKey(); if (pubkey) { diff --git a/src/hooks/useCurrentUser.ts b/src/hooks/useCurrentUser.ts index e79b3a3..18ce37c 100644 --- a/src/hooks/useCurrentUser.ts +++ b/src/hooks/useCurrentUser.ts @@ -3,6 +3,7 @@ import { useNostr } from '@nostrify/react'; import { useCallback, useMemo } from 'react'; import { useAuthor } from './useAuthor.ts'; +import { Nip07Signer } from '@/lib/Nip07Signer'; export function useCurrentUser() { const { nostr } = useNostr(); @@ -14,8 +15,8 @@ export function useCurrentUser() { return NUser.fromNsecLogin(login); case 'bunker': // Nostr login with NIP-46 "bunker://" URI return NUser.fromBunkerLogin(login, nostr); - case 'extension': // Nostr login with NIP-07 browser extension - return NUser.fromExtensionLogin(login); + case 'extension': // NIP-07 browser extension, pinned to this account where the extension can (getSigner) + return new NUser(login.type, login.pubkey, new Nip07Signer({ pubkey: login.pubkey })); // Other login types can be defined here default: throw new Error(`Unsupported login type: ${login.type}`); diff --git a/src/hooks/useLoginActions.ts b/src/hooks/useLoginActions.ts index ec1660f..3210b2b 100644 --- a/src/hooks/useLoginActions.ts +++ b/src/hooks/useLoginActions.ts @@ -8,6 +8,7 @@ import { } from '@nostrify/react/login'; import { useAppContext } from '@/hooks/useAppContext'; import { APP_RELAYS } from '@/lib/appRelays'; +import { getNip07Provider, hasConnect } from '@/lib/nip07'; // NOTE: This file should not be edited except for adding new login methods. @@ -40,8 +41,21 @@ export function useLoginActions() { const login = await NLogin.fromBunker(uri, nostr); addAndActivate(login); }, - // Login with a NIP-07 browser extension + // Login with a NIP-07 browser extension. One that can give the site an + // account of the user's choosing (connect) is asked for one; the + // extension shows the account itself. async extension(): Promise { + const provider = getNip07Provider(); + if (hasConnect(provider)) { + const signer = await provider.connect(); + const answer: unknown = await signer.getPublicKey(); + const pubkey = typeof answer === 'string' ? answer.toLowerCase() : ''; + if (!/^[0-9a-f]{64}$/.test(pubkey)) { + throw new Error('The extension returned an invalid public key'); + } + addAndActivate(new NLogin('extension', pubkey, null)); + return; + } const login = await NLogin.fromExtension(); addAndActivate(login); }, diff --git a/src/lib/Nip07Signer.ts b/src/lib/Nip07Signer.ts new file mode 100644 index 0000000..7888323 --- /dev/null +++ b/src/lib/Nip07Signer.ts @@ -0,0 +1,116 @@ +import type { NostrEvent, NostrSigner } from '@nostrify/types'; +import { verifyEvent } from 'nostr-tools'; + +import { awaitNip07Provider, getNip07Provider, hasGetSigner, type Nip07Provider } from '@/lib/nip07'; + +/** + * A NIP-07 browser-extension signer, normalizing behavior across extensions + * as Nostrify's `NBrowserSigner` does. + * + * Given the login's `pubkey`, it acts as that account through the + * extension's `getSigner(pubkey)` where the extension offers it (Din and + * Tenna do), so switching accounts in the extension doesn't change who the + * app signs as. A `NotFoundError` from `getSigner` (the extension no longer + * gives this site that account) is passed on, never answered by acting as + * another account. Extensions without `getSigner` are called directly. + */ +export class Nip07Signer implements NostrSigner { + readonly #pubkey: string | undefined; + readonly #timeout: number; + #pinned: Promise | undefined; + + constructor(opts?: { pubkey?: string; timeout?: number }) { + this.#pubkey = opts?.pubkey; + this.#timeout = opts?.timeout ?? 3000; + } + + /** The signer to call: pinned to the login's account when the extension can, else `window.nostr`. */ + protected async signer(): Promise { + const nostr = await awaitNip07Provider(this.#timeout); + if (!this.#pubkey || !hasGetSigner(nostr)) return nostr; + if (!this.#pinned) { + const pinned = nostr.getSigner(this.#pubkey); + this.#pinned = pinned; + // Ask again next time: the account may be given back to the site. + pinned.catch(() => { + if (this.#pinned === pinned) this.#pinned = undefined; + }); + } + return this.#pinned; + } + + async getPublicKey(): Promise { + const pubkey = await (await this.signer()).getPublicKey(); + if (typeof pubkey !== 'string') { + throw new Error(`Nostr public key retrieval failed: expected string, got ${JSON.stringify(pubkey)}`); + } + return pubkey; + } + + async signEvent(event: Omit): Promise { + const signed = await (await this.signer()).signEvent(event); + if (typeof signed !== 'object' || !signed || !signed.id || !signed.pubkey || !signed.sig) { + throw new Error( + `Nostr event signing failed: expected object with id, pubkey, and sig, got ${JSON.stringify(signed)}`, + ); + } + // Rebuilt from the NIP-01 fields alone, which also drops nostr-tools' + // cached `verifiedSymbol`, so the signature is really checked. + const normalized: NostrEvent = { + id: signed.id, + pubkey: signed.pubkey, + kind: signed.kind, + content: signed.content, + tags: signed.tags, + created_at: signed.created_at, + sig: signed.sig, + }; + if (!verifyEvent(normalized)) { + throw new Error('Nostr event signing failed: the extension returned an invalid event'); + } + return normalized; + } + + async getRelays(): Promise> { + const signer = await this.signer(); + if (!signer.getRelays) return {}; + const relays = await signer.getRelays(); + if (typeof relays !== 'object' || relays === null) { + throw new Error(`Nostr getRelays failed: expected object, got ${JSON.stringify(relays)}`); + } + return relays; + } + + get nip04(): NostrSigner['nip04'] { + return this.#cipher('nip04', 'NIP-04'); + } + + get nip44(): NostrSigner['nip44'] { + return this.#cipher('nip44', 'NIP-44'); + } + + /** + * Undefined when a loaded extension lacks the scheme; otherwise (including + * before the extension has loaded) a wrapper that waits for it. + */ + #cipher(scheme: 'nip04' | 'nip44', label: string): NostrSigner['nip44'] { + const loaded = getNip07Provider(); + if (loaded && !loaded[scheme]) return undefined; + + const run = async (op: 'encrypt' | 'decrypt', pubkey: string, text: string): Promise => { + const what = `${label} ${op === 'encrypt' ? 'encryption' : 'decryption'}`; + const cipher = (await this.signer())[scheme]; + if (!cipher) throw new Error(`${what} not supported by extension`); + const result = await cipher[op](pubkey, text); + if (typeof result !== 'string') { + throw new Error(`${what} failed: expected string result, got ${JSON.stringify(result)}`); + } + return result; + }; + + return { + encrypt: (pubkey, plaintext) => run('encrypt', pubkey, plaintext), + decrypt: (pubkey, ciphertext) => run('decrypt', pubkey, ciphertext), + }; + } +} diff --git a/src/lib/nip07.ts b/src/lib/nip07.ts new file mode 100644 index 0000000..f0e4232 --- /dev/null +++ b/src/lib/nip07.ts @@ -0,0 +1,75 @@ +import type { NostrSigner } from '@nostrify/types'; + +/** + * The NIP-07 provider at `window.nostr`, with the optional multi-account + * additions some providers (Din, Tenna) offer. Each may be missing, so check + * for it before calling it: + * + * - `connect()` asks the user to give the site an account and resolves with + * a signer for it. It always asks, so the provider shows the account. + * - `getSigner(pubkey)` resolves, without asking, with a signer pinned to an + * account the site holds, whatever account the provider itself is acting + * as. It rejects with a `NotFoundError` DOMException if the site doesn't + * hold that account. + * - `disconnect(pubkey)` lets the site's account go, without asking. + * + * A signer from `connect` or `getSigner` keeps its account, and its + * `getPublicKey()` answers without asking, even once the site no longer + * holds the account. Its other methods then reject with `NotFoundError`. + */ +export interface Nip07Provider extends NostrSigner { + connect?(): Promise; + getSigner?(pubkey: string): Promise; + disconnect?(pubkey: string): Promise; + signPsbt?(psbtHex: string): Promise; +} + +/** The provider at `window.nostr`, if one has been injected. */ +export function getNip07Provider(): Nip07Provider | undefined { + const provider = (globalThis as { nostr?: unknown }).nostr; + if (provider && typeof (provider as Nip07Provider).getPublicKey === 'function') { + return provider as Nip07Provider; + } + return undefined; +} + +/** Whether the provider can ask the user for an account to give the site. */ +export function hasConnect( + provider: Nip07Provider | undefined, +): provider is Nip07Provider & Required> { + return typeof provider?.connect === 'function'; +} + +/** Whether the provider can hand out signers pinned to an account. */ +export function hasGetSigner( + provider: Nip07Provider | undefined, +): provider is Nip07Provider & Required> { + return typeof provider?.getSigner === 'function'; +} + +/** Whether the provider lets the site give an account back. */ +export function hasDisconnect( + provider: Nip07Provider | undefined, +): provider is Nip07Provider & Required> { + return typeof provider?.disconnect === 'function'; +} + +/** Wait for `window.nostr`, polling every 100 ms up to `timeout`. */ +export function awaitNip07Provider(timeout = 3000): Promise { + const provider = getNip07Provider(); + if (provider) return Promise.resolve(provider); + + const deadline = Date.now() + timeout; + return new Promise((resolve, reject) => { + const interval = setInterval(() => { + const provider = getNip07Provider(); + if (provider) { + clearInterval(interval); + resolve(provider); + } else if (Date.now() >= deadline) { + clearInterval(interval); + reject(new Error('Browser extension not available')); + } + }, 100); + }); +}