mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Use window.nostr.connect, getSigner and disconnect where the extension offers them
Din's and Tenna's NIP-07 providers add three optional methods, after NIP-46's names. Logging in through an extension now asks connect() for an account (skipping the Welcome back preview, since the extension shows the account), each extension login signs through getSigner(pubkey) so switching accounts in the extension doesn't change who the app signs as, and logging out calls disconnect(pubkey). Each is feature-detected on its own; extensions without them work as before. The onchain-bitcoin skill's NBrowserSignerBtc now builds on the same signer.
This commit is contained in:
10 files changed
+262
-33
No files matched your search
@@ -133,7 +133,7 @@ export function useCurrentUser() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
case 'extension':
|
case 'extension':
|
||||||
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc());
|
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc({ pubkey: login.pubkey }));
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unsupported login type: ${login.type}`);
|
throw new Error(`Unsupported login type: ${login.type}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import type { NostrSigner } from '@nostrify/types';
|
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 type { NConnectSignerOpts } from '@nostrify/nostrify';
|
||||||
|
|
||||||
import { signPsbtLocal } from '@/lib/bitcoin';
|
import { signPsbtLocal } from '@/lib/bitcoin';
|
||||||
|
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// BtcSigner interface
|
// 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
|
* Calls the extension's `signPsbt` method if available. If the extension does
|
||||||
* not expose `signPsbt`, an error is thrown with a user-friendly message.
|
* not expose `signPsbt`, an error is thrown with a user-friendly message.
|
||||||
*/
|
*/
|
||||||
export class NBrowserSignerBtc extends NBrowserSigner implements BtcSigner {
|
export class NBrowserSignerBtc extends Nip07Signer implements BtcSigner {
|
||||||
constructor(opts?: { timeout?: number }) {
|
constructor(opts?: { pubkey?: string; timeout?: number }) {
|
||||||
super(opts);
|
super(opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
async signPsbt(psbtHex: string): Promise<string> {
|
async signPsbt(psbtHex: string): Promise<string> {
|
||||||
// `awaitNostr` is TypeScript-private but JavaScript-public at runtime.
|
const signer = await this.signer();
|
||||||
const nostr = await (this as unknown as { awaitNostr(): Promise<Record<string, unknown>> }).awaitNostr();
|
|
||||||
|
|
||||||
if (typeof nostr.signPsbt !== 'function') {
|
if (typeof signer.signPsbt !== 'function') {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"Your browser extension doesn't support sending Bitcoin. Try a different extension, or log in with your secret key.",
|
"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<string>;
|
return signer.signPsbt(psbtHex);
|
||||||
return signPsbt(psbtHex);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
## 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.
|
- **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/`.
|
- **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.
|
- **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`.
|
- **NIP-19 routing:** `npub`, `nprofile`, `note`, `nevent` and `naddr` identifiers are routed at the URL root to `src/pages/NIP19Page.tsx`.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { NostrContext } from '@nostrify/react';
|
|||||||
import { NUser, useNostrLogin } from '@nostrify/react/login';
|
import { NUser, useNostrLogin } from '@nostrify/react/login';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||||
|
|
||||||
interface NostrProviderProps {
|
interface NostrProviderProps {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -106,7 +107,8 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
case 'bunker':
|
case 'bunker':
|
||||||
return NUser.fromBunkerLogin(currentLogin, pool).signer;
|
return NUser.fromBunkerLogin(currentLogin, pool).signer;
|
||||||
case 'extension':
|
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:
|
default:
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useEffect } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
|
import { useNostrLogin } from '@nostrify/react/login';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { parseBlossomServerList } from '@/lib/appBlossom';
|
import { parseBlossomServerList } from '@/lib/appBlossom';
|
||||||
|
import { getNip07Provider, hasDisconnect } from '@/lib/nip07';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NostrSync - Syncs user's Nostr data
|
* NostrSync - Syncs user's Nostr data
|
||||||
@@ -11,11 +13,31 @@ import { parseBlossomServerList } from '@/lib/appBlossom';
|
|||||||
* Currently syncs:
|
* Currently syncs:
|
||||||
* - NIP-65 relay list (kind 10002)
|
* - NIP-65 relay list (kind 10002)
|
||||||
* - BUD-03 Blossom server list (kind 10063)
|
* - 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() {
|
export function NostrSync() {
|
||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { config, updateConfig } = useAppContext();
|
const { config, updateConfig } = useAppContext();
|
||||||
|
const { logins } = useNostrLogin();
|
||||||
|
const extensionLogins = useRef<Set<string>>(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(() => {
|
useEffect(() => {
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
|
|||||||
@@ -3,26 +3,11 @@ import { Button } from '@/components/ui/button.tsx';
|
|||||||
import AuthDialog from './AuthDialog';
|
import AuthDialog from './AuthDialog';
|
||||||
import { QuickLoginDialog } from './QuickLoginDialog';
|
import { QuickLoginDialog } from './QuickLoginDialog';
|
||||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||||
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
|
import { getNip07Provider, hasConnect } from '@/lib/nip07';
|
||||||
import { AccountSwitcher } from './AccountSwitcher';
|
import { AccountSwitcher } from './AccountSwitcher';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
/** Minimal shape of the NIP-07 provider injected at `window.nostr`. */
|
|
||||||
interface Nip07Provider {
|
|
||||||
getPublicKey(): Promise<string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
export interface LoginAreaProps {
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
@@ -31,10 +16,22 @@ export function LoginArea({ className }: LoginAreaProps) {
|
|||||||
const { currentUser } = useLoggedInAccounts();
|
const { currentUser } = useLoggedInAccounts();
|
||||||
const [authDialogOpen, setAuthDialogOpen] = useState(false);
|
const [authDialogOpen, setAuthDialogOpen] = useState(false);
|
||||||
const [quickLoginPubkey, setQuickLoginPubkey] = useState<string | null>(null);
|
const [quickLoginPubkey, setQuickLoginPubkey] = useState<string | null>(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 handleJoin = async () => {
|
||||||
const provider = getNip07Provider();
|
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 {
|
try {
|
||||||
const pubkey = await provider.getPublicKey();
|
const pubkey = await provider.getPublicKey();
|
||||||
if (pubkey) {
|
if (pubkey) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useNostr } from '@nostrify/react';
|
|||||||
import { useCallback, useMemo } from 'react';
|
import { useCallback, useMemo } from 'react';
|
||||||
|
|
||||||
import { useAuthor } from './useAuthor.ts';
|
import { useAuthor } from './useAuthor.ts';
|
||||||
|
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||||
|
|
||||||
export function useCurrentUser() {
|
export function useCurrentUser() {
|
||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
@@ -14,8 +15,8 @@ export function useCurrentUser() {
|
|||||||
return NUser.fromNsecLogin(login);
|
return NUser.fromNsecLogin(login);
|
||||||
case 'bunker': // Nostr login with NIP-46 "bunker://" URI
|
case 'bunker': // Nostr login with NIP-46 "bunker://" URI
|
||||||
return NUser.fromBunkerLogin(login, nostr);
|
return NUser.fromBunkerLogin(login, nostr);
|
||||||
case 'extension': // Nostr login with NIP-07 browser extension
|
case 'extension': // NIP-07 browser extension, pinned to this account where the extension can (getSigner)
|
||||||
return NUser.fromExtensionLogin(login);
|
return new NUser(login.type, login.pubkey, new Nip07Signer({ pubkey: login.pubkey }));
|
||||||
// Other login types can be defined here
|
// Other login types can be defined here
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unsupported login type: ${login.type}`);
|
throw new Error(`Unsupported login type: ${login.type}`);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
} from '@nostrify/react/login';
|
} from '@nostrify/react/login';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { APP_RELAYS } from '@/lib/appRelays';
|
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.
|
// 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);
|
const login = await NLogin.fromBunker(uri, nostr);
|
||||||
addAndActivate(login);
|
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<void> {
|
async extension(): Promise<void> {
|
||||||
|
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();
|
const login = await NLogin.fromExtension();
|
||||||
addAndActivate(login);
|
addAndActivate(login);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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<NostrSigner> | 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<Nip07Provider> {
|
||||||
|
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<string> {
|
||||||
|
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<NostrEvent, 'id' | 'pubkey' | 'sig'>): Promise<NostrEvent> {
|
||||||
|
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<Record<string, { read: boolean; write: boolean }>> {
|
||||||
|
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<string> => {
|
||||||
|
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),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<NostrSigner>;
|
||||||
|
getSigner?(pubkey: string): Promise<NostrSigner>;
|
||||||
|
disconnect?(pubkey: string): Promise<void>;
|
||||||
|
signPsbt?(psbtHex: string): Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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<Pick<Nip07Provider, 'connect'>> {
|
||||||
|
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<Pick<Nip07Provider, 'getSigner'>> {
|
||||||
|
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<Pick<Nip07Provider, 'disconnect'>> {
|
||||||
|
return typeof provider?.disconnect === 'function';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for `window.nostr`, polling every 100 ms up to `timeout`. */
|
||||||
|
export function awaitNip07Provider(timeout = 3000): Promise<Nip07Provider> {
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user