@formstr/signer 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +275 -0
- package/dist/index.cjs +726 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +140 -0
- package/dist/index.d.ts +140 -0
- package/dist/index.js +693 -0
- package/dist/index.js.map +1 -0
- package/dist/signer-DiKj4PR7.d.cts +377 -0
- package/dist/signer-DiKj4PR7.d.ts +377 -0
- package/dist/ui/index.cjs +334 -0
- package/dist/ui/index.cjs.map +1 -0
- package/dist/ui/index.d.cts +24 -0
- package/dist/ui/index.d.ts +24 -0
- package/dist/ui/index.js +298 -0
- package/dist/ui/index.js.map +1 -0
- package/package.json +85 -0
- package/styles/signer.css +263 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/signer.ts","../src/core/storage.ts","../src/core/localSigner.ts","../src/nip49.ts","../src/nip07.ts","../src/nip46.ts","../src/nip55.ts"],"sourcesContent":["import { getPublicKey, nip19 } from 'nostr-tools';\nimport type {\n ActiveSigner,\n BunkerLoginOptions,\n NostrConnectOptions,\n SignerConfig,\n SignerEvent,\n StoredAccount,\n} from './types.js';\nimport { localStorageAdapter, type StorageAdapter } from './storage.js';\nimport { LocalSigner } from './localSigner.js';\nimport { decryptNcryptsec, generateAccount } from '../nip49.js';\nimport { ExtensionSigner } from '../nip07.js';\nimport { bytesToHex, connectWithBunkerUri, initiateNostrConnect } from '../nip46.js';\nimport {\n loginWithAndroidSigner as connectWithAndroidSigner,\n type AndroidLoginOptions,\n type AndroidSignerAppInfo,\n type AndroidSignerPlugin,\n} from '../nip55.js';\n\nconst ACCOUNTS_KEY = 'accounts';\nconst ACTIVE_KEY = 'active-pubkey';\n\n/**\n * Multi-account Nostr signer with persistence.\n *\n * **Hydration.** The constructor reads previously-saved accounts from\n * the configured storage adapter. Every hydrated account starts\n * **locked**: present in `listAccounts()` and (if it was the active one\n * before) reachable via `getActiveAccount()`, but `getActiveSigner()`\n * returns `null` until the user re-authenticates. The matching\n * `loginWith*` method unlocks the active account.\n *\n * **Locked vs unlocked.** Use `getActiveAccount()` to render UI (\"logged\n * in as @alice\") and `getActiveSigner()` to decide whether the user can\n * actually sign. The pattern is \"show the account always, gate signing\n * on the signer.\"\n *\n * **Events.** Subscribe via `onChange()` to re-render when an account\n * is added, switched, or removed. See {@link SignerEvent}.\n */\nexport class Signer {\n readonly #storage: StorageAdapter;\n readonly #defaultAndroidPlugin: AndroidSignerPlugin | undefined;\n readonly #appMetadata: { name?: string; url?: string; image?: string };\n #accounts: StoredAccount[] = [];\n #activePubkey: string | null = null;\n #activeSigner: ActiveSigner | null = null;\n #listeners = new Set<(event: SignerEvent) => void>();\n\n constructor(config: SignerConfig = {}) {\n this.#storage = config.storage ?? localStorageAdapter(config.storageKeyPrefix);\n this.#defaultAndroidPlugin = config.androidSignerPlugin;\n this.#appMetadata = {\n name: config.appName,\n url: config.appUrl,\n image: config.appImage,\n };\n this.#hydrate();\n }\n\n #hydrate(): void {\n try {\n const raw = this.#storage.get(ACCOUNTS_KEY);\n if (raw) {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) this.#accounts = parsed as StoredAccount[];\n }\n this.#activePubkey = this.#storage.get(ACTIVE_KEY);\n } catch {\n this.#accounts = [];\n this.#activePubkey = null;\n }\n }\n\n #persistAccounts(): void {\n this.#storage.set(ACCOUNTS_KEY, JSON.stringify(this.#accounts));\n }\n\n #persistActive(): void {\n if (this.#activePubkey) this.#storage.set(ACTIVE_KEY, this.#activePubkey);\n else this.#storage.remove(ACTIVE_KEY);\n }\n\n #upsertAccount(account: StoredAccount): void {\n const idx = this.#accounts.findIndex(a => a.pubkey === account.pubkey);\n if (idx >= 0) this.#accounts[idx] = account;\n else this.#accounts.push(account);\n this.#persistAccounts();\n }\n\n #setActive(account: StoredAccount, signer: ActiveSigner): void {\n const wasDifferent = this.#activePubkey !== null && this.#activePubkey !== account.pubkey;\n this.#activePubkey = account.pubkey;\n this.#activeSigner = signer;\n this.#persistActive();\n this.#emit({ type: wasDifferent ? 'switch' : 'login', account });\n }\n\n #emit(event: SignerEvent): void {\n for (const cb of this.#listeners) {\n try {\n cb(event);\n } catch {\n // listener errors are swallowed so one bad listener can't break others\n }\n }\n }\n\n /**\n * Generate a brand-new nsec, encrypt it with `passphrase` (NIP-49),\n * persist the resulting `ncryptsec` account, and activate it. Returns\n * the new account's `npub` and `ncryptsec` — the caller must surface\n * the `ncryptsec` to the user **immediately** since it is the only way\n * back into the account on a fresh device.\n *\n * @throws if `passphrase` is empty.\n */\n async createAccount(passphrase: string): Promise<{ npub: string; ncryptsec: string }> {\n if (!passphrase) throw new Error('createAccount: passphrase required');\n const { secretKey, pubkey, npub, ncryptsec } = generateAccount(passphrase);\n const account: StoredAccount = { npub, pubkey, method: 'ncryptsec', ncryptsec };\n this.#upsertAccount(account);\n this.#setActive(account, new LocalSigner(secretKey));\n return { npub, ncryptsec };\n }\n\n /**\n * Decrypt an ncryptsec with the user's passphrase, persist the account\n * (overwriting any previous entry for the same pubkey), and activate it.\n *\n * @throws if either argument is empty, or if the passphrase doesn't\n * decrypt the ncryptsec.\n */\n async loginWithNcryptsec(ncryptsec: string, passphrase: string): Promise<StoredAccount> {\n if (!ncryptsec) throw new Error('loginWithNcryptsec: ncryptsec required');\n if (!passphrase) throw new Error('loginWithNcryptsec: passphrase required');\n const secretKey = decryptNcryptsec(ncryptsec, passphrase);\n const pubkey = getPublicKey(secretKey);\n const npub = nip19.npubEncode(pubkey);\n const account: StoredAccount = { npub, pubkey, method: 'ncryptsec', ncryptsec };\n this.#upsertAccount(account);\n this.#setActive(account, new LocalSigner(secretKey));\n return account;\n }\n\n /**\n * Connect via the NIP-07 browser extension exposed at `window.nostr`.\n * The extension prompts the user for permission on first use.\n *\n * @throws if no extension is installed or the user denies the request.\n */\n async loginWithExtension(): Promise<StoredAccount> {\n const extension = new ExtensionSigner();\n const pubkey = await extension.getPublicKey();\n const npub = nip19.npubEncode(pubkey);\n const account: StoredAccount = { npub, pubkey, method: 'extension' };\n this.#upsertAccount(account);\n this.#setActive(account, extension);\n return account;\n }\n\n /**\n * Connect to a NIP-46 remote signer via a `bunker://` URI. Relays are\n * read from the URI itself — no hardcoded fallbacks. Pass a `pool`\n * to reuse an existing relay connection; pass `clientSecretKey` to\n * resume a previous session (the hex from `StoredAccount.nip46`).\n *\n * @throws if the URI is malformed, no relay is reachable, or the\n * remote signer rejects pairing within the implementation's timeout.\n */\n async loginWithBunkerUri(\n uri: string,\n options: BunkerLoginOptions = {},\n ): Promise<StoredAccount> {\n const result = await connectWithBunkerUri(uri, options);\n const npub = nip19.npubEncode(result.pubkey);\n const account: StoredAccount = {\n npub,\n pubkey: result.pubkey,\n method: 'nip46',\n nip46: {\n uri,\n remoteSignerPubkey: result.pointer.pubkey,\n relays: result.pointer.relays,\n clientSecretKey: bytesToHex(result.clientSecretKey),\n },\n };\n this.#upsertAccount(account);\n this.#setActive(account, result.signer);\n return account;\n }\n\n /**\n * Initiate a NIP-46 `nostrconnect://` pairing. Generates a client\n * keypair, publishes a connect request to the supplied `relays`, and\n * waits for a remote signer to pair. Call `options.onUri(uri)` to\n * render the URI as a QR code; the returned promise resolves once\n * pairing completes. Cancel by aborting `options.signal`.\n *\n * @throws if `relays` is empty, the user aborts, the pairing times\n * out, or no signer responds.\n */\n async loginWithNostrConnect(options: NostrConnectOptions): Promise<StoredAccount> {\n if (options.relays.length === 0) {\n throw new Error('loginWithNostrConnect: at least one relay required');\n }\n // Merge per-call metadata over SignerConfig defaults (appName/url/image).\n // `name` is required — Amber (and likely other NIP-55 signer apps) gate\n // the consent UI on having a recognizable client identity in the URI.\n // Without one they will receive the request but never surface\n // approve/deny buttons, leaving the pairing silently stuck.\n const metadata = {\n name: options.metadata?.name ?? this.#appMetadata.name,\n url: options.metadata?.url ?? this.#appMetadata.url,\n image: options.metadata?.image ?? this.#appMetadata.image,\n };\n if (!metadata.name) {\n throw new Error(\n '@formstr/signer: loginWithNostrConnect requires an app name. Set `appName` in createSigner() or pass `metadata.name` to loginWithNostrConnect().',\n );\n }\n const init = initiateNostrConnect({\n relays: options.relays,\n metadata,\n perms: options.perms,\n pool: options.pool,\n onAuth: options.onAuth,\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n onRelayMismatch: options.onRelayMismatch,\n });\n options.onUri(init.uri);\n const result = await init.complete;\n const npub = nip19.npubEncode(result.pubkey);\n const account: StoredAccount = {\n npub,\n pubkey: result.pubkey,\n method: 'nip46',\n nip46: {\n uri: init.uri,\n remoteSignerPubkey: result.pointer.pubkey,\n relays: result.pointer.relays,\n clientSecretKey: bytesToHex(result.clientSecretKey),\n },\n };\n this.#upsertAccount(account);\n this.#setActive(account, result.signer);\n return account;\n }\n\n /**\n * Enumerate NIP-55 signer apps installed on the device, via the\n * configured Android plugin (or `plugin` if supplied). Useful for\n * rendering a \"pick your signer\" list — the built-in UI does this\n * automatically when the Android tab is selected.\n *\n * Only meaningful inside a Capacitor Android shell. On web/iOS the\n * configured plugin is typically absent and this throws.\n *\n * @throws if no plugin is configured and none is passed in.\n */\n async listAndroidSignerApps(\n plugin?: AndroidSignerPlugin,\n ): Promise<AndroidSignerAppInfo[]> {\n const p = plugin ?? this.#defaultAndroidPlugin;\n if (!p) {\n throw new Error(\n '@formstr/signer: no Android signer plugin configured (pass `androidSignerPlugin` to createSigner or `plugin` to listAndroidSignerApps)',\n );\n }\n const { apps } = await p.getInstalledSignerApps();\n return apps;\n }\n\n /**\n * Sign in via a NIP-55 Android external signer (Amber, etc). If\n * `options.packageName` is given, that specific signer app is invoked;\n * otherwise the plugin picks a default (typically the only installed\n * signer, or an OS chooser). Pass `options.plugin` to override the\n * configured default for this call.\n *\n * @throws if no plugin is configured, the signer app cannot be\n * resolved to a package name, or the user denies the request.\n */\n async loginWithAndroidSigner(options: AndroidLoginOptions = {}): Promise<StoredAccount> {\n const plugin = options.plugin ?? this.#defaultAndroidPlugin;\n if (!plugin) {\n throw new Error(\n '@formstr/signer: no Android signer plugin configured (pass `androidSignerPlugin` to createSigner or `plugin` to loginWithAndroidSigner)',\n );\n }\n const result = await connectWithAndroidSigner(plugin, options.packageName);\n const account: StoredAccount = {\n npub: result.npub,\n pubkey: result.pubkey,\n method: 'android',\n androidPackageName: result.packageName,\n };\n this.#upsertAccount(account);\n this.#setActive(account, result.signer);\n return account;\n }\n\n /** Snapshot of every persisted account, in insertion order. */\n listAccounts(): StoredAccount[] {\n return [...this.#accounts];\n }\n\n /**\n * The currently selected account, or `null` if none. Present even when\n * the account is locked (no active signer yet). Use this to render\n * \"logged in as @alice\" — pair with {@link getActiveSigner} to decide\n * whether signing is actually available.\n */\n getActiveAccount(): StoredAccount | null {\n if (!this.#activePubkey) return null;\n return this.#accounts.find(a => a.pubkey === this.#activePubkey) ?? null;\n }\n\n /**\n * The unlocked signer for the active account, or `null` if locked.\n * After a fresh page load this is `null` for every account type\n * (passphrase / extension grant / signer-app handshake all need to\n * be redone). Calling the matching `loginWith*` method unlocks it.\n */\n getActiveSigner(): ActiveSigner | null {\n return this.#activeSigner;\n }\n\n /**\n * Make `pubkey` the active account. Clears the in-memory signer —\n * the new account starts **locked** even if it was previously\n * unlocked in this session.\n *\n * @throws if `pubkey` does not match any persisted account.\n */\n async switchAccount(pubkey: string): Promise<void> {\n const account = this.#accounts.find(a => a.pubkey === pubkey);\n if (!account) throw new Error(`switchAccount: no account for pubkey ${pubkey}`);\n this.#activePubkey = pubkey;\n this.#activeSigner = null;\n this.#persistActive();\n this.#emit({ type: 'switch', account });\n }\n\n /**\n * Remove an account from storage. `pubkey` defaults to the active\n * account. If the active account is removed, the in-memory signer is\n * cleared. No-op if there is nothing to remove.\n */\n async logout(pubkey?: string): Promise<void> {\n const target = pubkey ?? this.#activePubkey;\n if (!target) return;\n this.#accounts = this.#accounts.filter(a => a.pubkey !== target);\n this.#persistAccounts();\n if (this.#activePubkey === target) {\n this.#activePubkey = null;\n this.#activeSigner = null;\n this.#persistActive();\n }\n this.#emit({ type: 'logout', pubkey: target });\n }\n\n /**\n * Subscribe to account-state changes. Returns an unsubscribe function.\n * Listener errors are swallowed so one bad listener can't break others.\n * See {@link SignerEvent} for the variants.\n */\n onChange(cb: (event: SignerEvent) => void): () => void {\n this.#listeners.add(cb);\n return () => {\n this.#listeners.delete(cb);\n };\n }\n}\n\n/** Convenience wrapper around `new Signer(config)`. */\nexport function createSigner(config: SignerConfig = {}): Signer {\n return new Signer(config);\n}\n","export interface StorageAdapter {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\nconst DEFAULT_PREFIX = '@formstr/signer:';\n\nexport function localStorageAdapter(prefix: string = DEFAULT_PREFIX): StorageAdapter {\n const ls = (): Storage | null => {\n try {\n return typeof globalThis !== 'undefined' && globalThis.localStorage\n ? globalThis.localStorage\n : null;\n } catch {\n return null;\n }\n };\n return {\n get(key) {\n try {\n return ls()?.getItem(prefix + key) ?? null;\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n ls()?.setItem(prefix + key, value);\n } catch {\n // swallow quota / privacy-mode errors\n }\n },\n remove(key) {\n try {\n ls()?.removeItem(prefix + key);\n } catch {\n // swallow\n }\n },\n };\n}\n","import {\n finalizeEvent,\n getPublicKey,\n nip04,\n nip44,\n type Event as NostrEvent,\n type EventTemplate,\n} from 'nostr-tools';\nimport type { ActiveSigner } from './types.js';\n\n/**\n * ActiveSigner backed by a raw secret key held in memory.\n * The secret key never leaves this object — there is no getter for it.\n */\nexport class LocalSigner implements ActiveSigner {\n readonly #secretKey: Uint8Array;\n\n constructor(secretKey: Uint8Array) {\n this.#secretKey = secretKey;\n }\n\n async getPublicKey(): Promise<string> {\n return getPublicKey(this.#secretKey);\n }\n\n async signEvent(event: EventTemplate): Promise<NostrEvent> {\n return finalizeEvent(event, this.#secretKey);\n }\n\n async nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n return nip04.encrypt(this.#secretKey, peerPubkey, plaintext);\n }\n\n async nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n return nip04.decrypt(this.#secretKey, peerPubkey, ciphertext);\n }\n\n async nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n const key = nip44.v2.utils.getConversationKey(this.#secretKey, peerPubkey);\n return nip44.v2.encrypt(plaintext, key);\n }\n\n async nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n const key = nip44.v2.utils.getConversationKey(this.#secretKey, peerPubkey);\n return nip44.v2.decrypt(ciphertext, key);\n }\n}\n","import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';\nimport { encrypt as nip49Encrypt, decrypt as nip49Decrypt } from 'nostr-tools/nip49';\n\nexport function encryptSecretKey(secretKey: Uint8Array, passphrase: string): string {\n return nip49Encrypt(secretKey, passphrase);\n}\n\nexport function decryptNcryptsec(ncryptsec: string, passphrase: string): Uint8Array {\n return nip49Decrypt(ncryptsec, passphrase);\n}\n\nexport interface GeneratedAccount {\n secretKey: Uint8Array;\n pubkey: string;\n npub: string;\n ncryptsec: string;\n}\n\nexport function generateAccount(passphrase: string): GeneratedAccount {\n const secretKey = generateSecretKey();\n const pubkey = getPublicKey(secretKey);\n const npub = nip19.npubEncode(pubkey);\n const ncryptsec = nip49Encrypt(secretKey, passphrase);\n return { secretKey, pubkey, npub, ncryptsec };\n}\n","import type { Event as NostrEvent, EventTemplate } from 'nostr-tools';\nimport type { ActiveSigner } from './core/types.js';\n\nexport interface WindowNostr {\n getPublicKey(): Promise<string>;\n signEvent(event: EventTemplate): Promise<NostrEvent>;\n getRelays?(): Promise<Record<string, { read: boolean; write: boolean }>>;\n nip04?: {\n encrypt(peerPubkey: string, plaintext: string): Promise<string>;\n decrypt(peerPubkey: string, ciphertext: string): Promise<string>;\n };\n nip44?: {\n encrypt(peerPubkey: string, plaintext: string): Promise<string>;\n decrypt(peerPubkey: string, ciphertext: string): Promise<string>;\n };\n}\n\nexport function getWindowNostr(): WindowNostr {\n const nostr = (globalThis as { nostr?: WindowNostr }).nostr;\n if (!nostr) {\n throw new Error(\n '@formstr/signer: NIP-07 extension not found (globalThis.nostr is undefined)',\n );\n }\n return nostr;\n}\n\nexport class ExtensionSigner implements ActiveSigner {\n async getPublicKey(): Promise<string> {\n return getWindowNostr().getPublicKey();\n }\n\n async signEvent(event: EventTemplate): Promise<NostrEvent> {\n return getWindowNostr().signEvent(event);\n }\n\n async nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n const ext = getWindowNostr();\n if (!ext.nip04) throw new Error('NIP-07 extension does not expose nip04');\n return ext.nip04.encrypt(peerPubkey, plaintext);\n }\n\n async nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n const ext = getWindowNostr();\n if (!ext.nip04) throw new Error('NIP-07 extension does not expose nip04');\n return ext.nip04.decrypt(peerPubkey, ciphertext);\n }\n\n async nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n const ext = getWindowNostr();\n if (!ext.nip44) throw new Error('NIP-07 extension does not expose nip44');\n return ext.nip44.encrypt(peerPubkey, plaintext);\n }\n\n async nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n const ext = getWindowNostr();\n if (!ext.nip44) throw new Error('NIP-07 extension does not expose nip44');\n return ext.nip44.decrypt(peerPubkey, ciphertext);\n }\n}\n","import { generateSecretKey, getPublicKey } from 'nostr-tools';\nimport {\n BunkerSigner as ToolsBunkerSigner,\n createNostrConnectURI,\n parseBunkerInput,\n type BunkerPointer,\n} from 'nostr-tools/nip46';\nimport type { AbstractSimplePool } from 'nostr-tools/abstract-pool';\nimport type { Event as NostrEvent, EventTemplate } from 'nostr-tools';\nimport type { ActiveSigner, RelayMismatchHandler } from './core/types.js';\n\nexport type { BunkerPointer };\n\n/**\n * Thin wrapper around nostr-tools' BunkerSigner that exposes only the\n * ActiveSigner surface. We keep this layer so callers depend on a stable\n * interface even if we ever swap the underlying implementation.\n */\nexport class BunkerSigner implements ActiveSigner {\n readonly #delegate: ToolsBunkerSigner;\n\n constructor(delegate: ToolsBunkerSigner) {\n this.#delegate = delegate;\n }\n\n getPublicKey(): Promise<string> {\n return this.#delegate.getPublicKey();\n }\n signEvent(event: EventTemplate): Promise<NostrEvent> {\n return this.#delegate.signEvent(event);\n }\n nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n return this.#delegate.nip04Encrypt(peerPubkey, plaintext);\n }\n nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n return this.#delegate.nip04Decrypt(peerPubkey, ciphertext);\n }\n nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n return this.#delegate.nip44Encrypt(peerPubkey, plaintext);\n }\n nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n return this.#delegate.nip44Decrypt(peerPubkey, ciphertext);\n }\n async close(): Promise<void> {\n return this.#delegate.close();\n }\n}\n\nexport interface BunkerLoginOptions {\n /** Custom pool, e.g. for tests. Defaults to a new SimplePool inside nostr-tools. */\n pool?: AbstractSimplePool;\n /** Called when the remote signer needs the user to visit an auth URL. */\n onAuth?: (url: string) => void;\n /** Optional client session keypair (hex bytes). Auto-generated if omitted. */\n clientSecretKey?: Uint8Array;\n /** Notified when the bunker's preferred relays differ from the URI's. */\n onRelayMismatch?: RelayMismatchHandler;\n /**\n * NIP-46 permissions to request as the 3rd `connect` param\n * (e.g. `['sign_event:1', 'nip44_encrypt']`). When omitted, the\n * connect request carries no perms — bunker UIs may then skip the\n * approval prompt entirely, leaving the user with nothing to tap.\n */\n perms?: string[];\n}\n\nasync function fetchBunkerRelays(tools: ToolsBunkerSigner): Promise<string[] | null> {\n try {\n const resp = await tools.sendRequest('get_relays', []);\n const parsed = JSON.parse(resp) as unknown;\n if (Array.isArray(parsed)) {\n return parsed.filter((r): r is string => typeof r === 'string');\n }\n if (typeof parsed === 'object' && parsed !== null) {\n return Object.keys(parsed as Record<string, unknown>);\n }\n return null;\n } catch {\n return null;\n }\n}\n\nfunction relayListsMatch(a: string[], b: string[]): boolean {\n if (a.length !== b.length) return false;\n const sa = [...a].sort();\n const sb = [...b].sort();\n for (let i = 0; i < sa.length; i++) if (sa[i] !== sb[i]) return false;\n return true;\n}\n\nasync function resolveRelayChoice(\n tools: ToolsBunkerSigner,\n userRelays: string[],\n onRelayMismatch: RelayMismatchHandler | undefined,\n): Promise<string[]> {\n if (!onRelayMismatch) return userRelays;\n const bunkerRelays = await fetchBunkerRelays(tools);\n if (!bunkerRelays || relayListsMatch(userRelays, bunkerRelays)) return userRelays;\n const accept = await onRelayMismatch({ userRelays, bunkerRelays });\n return accept ? bunkerRelays : userRelays;\n}\n\nexport interface BunkerConnectResult {\n signer: BunkerSigner;\n pubkey: string;\n pointer: BunkerPointer;\n clientSecretKey: Uint8Array;\n}\n\n/**\n * Connect to a remote signer via a bunker:// URI (or a NIP-05 identifier).\n * Relays come from the URI — there is no fallback default list.\n */\nexport async function connectWithBunkerUri(\n uri: string,\n options: BunkerLoginOptions = {},\n): Promise<BunkerConnectResult> {\n const pointer = await parseBunkerInput(uri);\n if (!pointer) {\n throw new Error('@formstr/signer: invalid bunker URI');\n }\n if (!pointer.relays?.length) {\n throw new Error('@formstr/signer: bunker URI must include at least one relay');\n }\n const clientSecretKey = options.clientSecretKey ?? generateSecretKey();\n const tools = ToolsBunkerSigner.fromBunker(clientSecretKey, pointer, {\n pool: options.pool,\n onauth: options.onAuth,\n });\n // nostr-tools' BunkerSigner.connect() hardcodes only [pubkey, secret],\n // dropping the optional 3rd `perms` arg defined by NIP-46. Without it\n // bunker UIs (Amber, etc.) have no permissions to authorize and may\n // skip the approval prompt entirely. We send the request directly.\n await tools.sendRequest('connect', [\n pointer.pubkey,\n pointer.secret ?? '',\n (options.perms ?? []).join(','),\n ]);\n const pubkey = await tools.getPublicKey();\n const resolvedRelays = await resolveRelayChoice(\n tools,\n pointer.relays,\n options.onRelayMismatch,\n );\n return {\n signer: new BunkerSigner(tools),\n pubkey,\n pointer: { ...pointer, relays: resolvedRelays },\n clientSecretKey,\n };\n}\n\nexport interface NostrConnectInitOptions {\n /** User-supplied relays. The whole point of the strict-relay rule. */\n relays: string[];\n metadata?: { name?: string; url?: string; image?: string };\n /** Permissions to request (NIP-46 perms list, e.g. [\"sign_event:1\",\"nip44_encrypt\"]). */\n perms?: string[];\n pool?: AbstractSimplePool;\n onAuth?: (url: string) => void;\n /** Override the auto-generated client session keypair. */\n clientSecretKey?: Uint8Array;\n /** Override the auto-generated URI secret. */\n secret?: string;\n /** Abort the pairing wait. */\n signal?: AbortSignal;\n /** Max wait for pairing in ms (default 5 minutes). */\n timeoutMs?: number;\n /** Notified when the bunker's preferred relays differ from the user's. */\n onRelayMismatch?: RelayMismatchHandler;\n}\n\nexport interface NostrConnectInitiation {\n uri: string;\n clientPubkey: string;\n complete: Promise<BunkerConnectResult>;\n}\n\n/**\n * Generate a nostrconnect:// URI and wait for the remote signer to pair.\n * The caller displays the URI (typically as a QR code), and the returned\n * `complete` promise resolves once the signer connects back.\n */\nexport function initiateNostrConnect(options: NostrConnectInitOptions): NostrConnectInitiation {\n if (options.relays.length === 0) {\n throw new Error('@formstr/signer: at least one relay is required for nostrconnect');\n }\n const clientSecretKey = options.clientSecretKey ?? generateSecretKey();\n const clientPubkey = getPublicKey(clientSecretKey);\n const secret = options.secret ?? Math.random().toString(36).slice(2);\n const uri = createNostrConnectURI({\n clientPubkey,\n relays: options.relays,\n secret,\n perms: options.perms,\n name: options.metadata?.name,\n url: options.metadata?.url,\n image: options.metadata?.image,\n });\n const maxWaitOrAbort: number | AbortSignal =\n options.signal ?? options.timeoutMs ?? 300_000;\n // skipSwitchRelays:true — keep the caller-supplied relays authoritative,\n // never silently swap to whatever the bunker prefers.\n const complete = ToolsBunkerSigner.fromURI(\n clientSecretKey,\n uri,\n { pool: options.pool, onauth: options.onAuth, skipSwitchRelays: true },\n maxWaitOrAbort,\n ).then(async (tools) => {\n const pubkey = await tools.getPublicKey();\n const resolvedRelays = await resolveRelayChoice(\n tools,\n options.relays,\n options.onRelayMismatch,\n );\n return {\n signer: new BunkerSigner(tools),\n pubkey,\n pointer: { ...tools.bp, relays: resolvedRelays },\n clientSecretKey,\n };\n });\n return { uri, clientPubkey, complete };\n}\n\nconst hexAlphabet = '0123456789abcdef';\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += hexAlphabet[b >> 4] + hexAlphabet[b & 0xf];\n return s;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) throw new Error('hexToBytes: odd-length hex string');\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n","import { getEventHash, nip19, type Event as NostrEvent, type EventTemplate } from 'nostr-tools';\nimport type { ActiveSigner } from './core/types.js';\n\n/**\n * Subset of `nostr-signer-capacitor-plugin`'s exported `NostrSignerPlugin`\n * that we depend on. Signatures intentionally mirror that library\n * (positional args, per-call `packageName`) so the real plugin is\n * structurally assignable here — and any mock written against this\n * interface is a faithful stand-in. The conformance is enforced by a\n * compile-time guard in `tests/helpers/mockAndroidPlugin.ts`.\n */\nexport interface AndroidSignerAppInfo {\n name: string;\n packageName: string;\n iconUrl?: string;\n}\n\nexport interface AndroidSignerPlugin {\n setPackageName(packageName: string): Promise<void>;\n getInstalledSignerApps(): Promise<{ apps: AndroidSignerAppInfo[] }>;\n getPublicKey(\n packageName?: string,\n permissions?: string,\n ): Promise<{ npub: string; package: string }>;\n signEvent(\n packageName: string,\n eventJson: string,\n id: string,\n npub: string,\n ): Promise<{ signature: string; id: string; event: string }>;\n nip04Encrypt(\n packageName: string,\n plainText: string,\n id: string,\n pubKey: string,\n npub: string,\n ): Promise<{ result: string; id: string }>;\n nip04Decrypt(\n packageName: string,\n encryptedText: string,\n id: string,\n pubKey: string,\n npub: string,\n ): Promise<{ result: string; id: string }>;\n nip44Encrypt(\n packageName: string,\n plainText: string,\n id: string,\n pubKey: string,\n npub: string,\n ): Promise<{ result: string; id: string }>;\n nip44Decrypt(\n packageName: string,\n encryptedText: string,\n id: string,\n pubKey: string,\n npub: string,\n ): Promise<{ result: string; id: string }>;\n}\n\nexport interface AndroidLoginOptions {\n /** The Android package name of the external signer app (e.g. com.greenart7c3.nostrsigner). */\n packageName?: string;\n /** Override the plugin for this call. Falls back to SignerConfig.androidSignerPlugin. */\n plugin?: AndroidSignerPlugin;\n}\n\nexport class AndroidSigner implements ActiveSigner {\n readonly #plugin: AndroidSignerPlugin;\n readonly #packageName: string;\n readonly #npub: string;\n readonly #pubkey: string;\n\n constructor(\n plugin: AndroidSignerPlugin,\n packageName: string,\n npub: string,\n pubkey: string,\n ) {\n this.#plugin = plugin;\n this.#packageName = packageName;\n this.#npub = npub;\n this.#pubkey = pubkey;\n }\n\n async getPublicKey(): Promise<string> {\n return this.#pubkey;\n }\n\n async signEvent(event: EventTemplate): Promise<NostrEvent> {\n const unsigned = { ...event, pubkey: this.#pubkey };\n const eventId = getEventHash(unsigned);\n const result = await this.#plugin.signEvent(\n this.#packageName,\n JSON.stringify(unsigned),\n eventId,\n this.#npub,\n );\n return JSON.parse(result.event) as NostrEvent;\n }\n\n async nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n const { result } = await this.#plugin.nip04Encrypt(\n this.#packageName,\n plaintext,\n '',\n peerPubkey,\n this.#npub,\n );\n return result;\n }\n\n async nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n const { result } = await this.#plugin.nip04Decrypt(\n this.#packageName,\n ciphertext,\n '',\n peerPubkey,\n this.#npub,\n );\n return result;\n }\n\n async nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string> {\n const { result } = await this.#plugin.nip44Encrypt(\n this.#packageName,\n plaintext,\n '',\n peerPubkey,\n this.#npub,\n );\n return result;\n }\n\n async nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string> {\n const { result } = await this.#plugin.nip44Decrypt(\n this.#packageName,\n ciphertext,\n '',\n peerPubkey,\n this.#npub,\n );\n return result;\n }\n}\n\nexport interface AndroidLoginResult {\n signer: AndroidSigner;\n pubkey: string;\n npub: string;\n packageName: string;\n}\n\nexport async function loginWithAndroidSigner(\n plugin: AndroidSignerPlugin,\n packageName?: string,\n): Promise<AndroidLoginResult> {\n if (packageName) {\n await plugin.setPackageName(packageName);\n }\n const { npub, package: pluginPackage } = await plugin.getPublicKey(packageName);\n const resolvedPackage = pluginPackage || packageName;\n if (!resolvedPackage) {\n throw new Error(\n '@formstr/signer: android signer did not return a package name and none was supplied',\n );\n }\n const decoded = nip19.decode(npub);\n if (decoded.type !== 'npub') {\n throw new Error('@formstr/signer: android signer returned a non-npub identifier');\n }\n return {\n signer: new AndroidSigner(plugin, resolvedPackage, npub, decoded.data),\n pubkey: decoded.data,\n npub,\n packageName: resolvedPackage,\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,SAAAC,cAAa;;;ACMpC,IAAM,iBAAiB;AAEhB,SAAS,oBAAoB,SAAiB,gBAAgC;AACnF,QAAM,KAAK,MAAsB;AAC/B,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,eACnD,WAAW,eACX;AAAA,IACN,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AAAA,IACL,IAAI,KAAK;AACP,UAAI;AACF,eAAO,GAAG,GAAG,QAAQ,SAAS,GAAG,KAAK;AAAA,MACxC,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,IAAI,KAAK,OAAO;AACd,UAAI;AACF,WAAG,GAAG,QAAQ,SAAS,KAAK,KAAK;AAAA,MACnC,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,IACA,OAAO,KAAK;AACV,UAAI;AACF,WAAG,GAAG,WAAW,SAAS,GAAG;AAAA,MAC/B,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;;;ACzCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAOA,IAAM,cAAN,MAA0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;AAC9E,SAAK,gBAAgB;AACrB,SAAK,gBAAgB;AACrB,SAAK,eAAe;AACpB,SAAK,MAAM,EAAE,MAAM,UAAU,QAAQ,CAAC;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,OAAO,QAAgC;AAC3C,UAAM,SAAS,UAAU,KAAK;AAC9B,QAAI,CAAC,OAAQ;AACb,SAAK,YAAY,KAAK,UAAU,OAAO,OAAK,EAAE,WAAW,MAAM;AAC/D,SAAK,iBAAiB;AACtB,QAAI,KAAK,kBAAkB,QAAQ;AACjC,WAAK,gBAAgB;AACrB,WAAK,gBAAgB;AACrB,WAAK,eAAe;AAAA,IACtB;AACA,SAAK,MAAM,EAAE,MAAM,UAAU,QAAQ,OAAO,CAAC;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAS,IAA8C;AACrD,SAAK,WAAW,IAAI,EAAE;AACtB,WAAO,MAAM;AACX,WAAK,WAAW,OAAO,EAAE;AAAA,IAC3B;AAAA,EACF;AACF;AAGO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAC9D,SAAO,IAAI,OAAO,MAAM;AAC1B;","names":["getPublicKey","nip19","getPublicKey","generateSecretKey","getPublicKey","nip19","getPublicKey","nip19"]}
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { EventTemplate, Event } from 'nostr-tools';
|
|
2
|
+
import { AbstractSimplePool } from 'nostr-tools/abstract-pool';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Subset of `nostr-signer-capacitor-plugin`'s exported `NostrSignerPlugin`
|
|
6
|
+
* that we depend on. Signatures intentionally mirror that library
|
|
7
|
+
* (positional args, per-call `packageName`) so the real plugin is
|
|
8
|
+
* structurally assignable here — and any mock written against this
|
|
9
|
+
* interface is a faithful stand-in. The conformance is enforced by a
|
|
10
|
+
* compile-time guard in `tests/helpers/mockAndroidPlugin.ts`.
|
|
11
|
+
*/
|
|
12
|
+
interface AndroidSignerAppInfo {
|
|
13
|
+
name: string;
|
|
14
|
+
packageName: string;
|
|
15
|
+
iconUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
interface AndroidSignerPlugin {
|
|
18
|
+
setPackageName(packageName: string): Promise<void>;
|
|
19
|
+
getInstalledSignerApps(): Promise<{
|
|
20
|
+
apps: AndroidSignerAppInfo[];
|
|
21
|
+
}>;
|
|
22
|
+
getPublicKey(packageName?: string, permissions?: string): Promise<{
|
|
23
|
+
npub: string;
|
|
24
|
+
package: string;
|
|
25
|
+
}>;
|
|
26
|
+
signEvent(packageName: string, eventJson: string, id: string, npub: string): Promise<{
|
|
27
|
+
signature: string;
|
|
28
|
+
id: string;
|
|
29
|
+
event: string;
|
|
30
|
+
}>;
|
|
31
|
+
nip04Encrypt(packageName: string, plainText: string, id: string, pubKey: string, npub: string): Promise<{
|
|
32
|
+
result: string;
|
|
33
|
+
id: string;
|
|
34
|
+
}>;
|
|
35
|
+
nip04Decrypt(packageName: string, encryptedText: string, id: string, pubKey: string, npub: string): Promise<{
|
|
36
|
+
result: string;
|
|
37
|
+
id: string;
|
|
38
|
+
}>;
|
|
39
|
+
nip44Encrypt(packageName: string, plainText: string, id: string, pubKey: string, npub: string): Promise<{
|
|
40
|
+
result: string;
|
|
41
|
+
id: string;
|
|
42
|
+
}>;
|
|
43
|
+
nip44Decrypt(packageName: string, encryptedText: string, id: string, pubKey: string, npub: string): Promise<{
|
|
44
|
+
result: string;
|
|
45
|
+
id: string;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
interface AndroidLoginOptions {
|
|
49
|
+
/** The Android package name of the external signer app (e.g. com.greenart7c3.nostrsigner). */
|
|
50
|
+
packageName?: string;
|
|
51
|
+
/** Override the plugin for this call. Falls back to SignerConfig.androidSignerPlugin. */
|
|
52
|
+
plugin?: AndroidSignerPlugin;
|
|
53
|
+
}
|
|
54
|
+
declare class AndroidSigner implements ActiveSigner {
|
|
55
|
+
#private;
|
|
56
|
+
constructor(plugin: AndroidSignerPlugin, packageName: string, npub: string, pubkey: string);
|
|
57
|
+
getPublicKey(): Promise<string>;
|
|
58
|
+
signEvent(event: EventTemplate): Promise<Event>;
|
|
59
|
+
nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string>;
|
|
60
|
+
nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string>;
|
|
61
|
+
nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string>;
|
|
62
|
+
nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string>;
|
|
63
|
+
}
|
|
64
|
+
interface AndroidLoginResult {
|
|
65
|
+
signer: AndroidSigner;
|
|
66
|
+
pubkey: string;
|
|
67
|
+
npub: string;
|
|
68
|
+
packageName: string;
|
|
69
|
+
}
|
|
70
|
+
declare function loginWithAndroidSigner(plugin: AndroidSignerPlugin, packageName?: string): Promise<AndroidLoginResult>;
|
|
71
|
+
|
|
72
|
+
interface StorageAdapter {
|
|
73
|
+
get(key: string): string | null;
|
|
74
|
+
set(key: string, value: string): void;
|
|
75
|
+
remove(key: string): void;
|
|
76
|
+
}
|
|
77
|
+
declare function localStorageAdapter(prefix?: string): StorageAdapter;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* How the user's key material is held for an account:
|
|
81
|
+
* - `extension`: NIP-07 browser extension (window.nostr).
|
|
82
|
+
* - `nip46`: NIP-46 remote signer (bunker URI or nostrconnect QR).
|
|
83
|
+
* - `ncryptsec`: NIP-49 encrypted nsec — decrypted into memory on unlock.
|
|
84
|
+
* - `android`: NIP-55 Android external signer app via a Capacitor plugin.
|
|
85
|
+
*/
|
|
86
|
+
type LoginMethod = 'extension' | 'nip46' | 'ncryptsec' | 'android';
|
|
87
|
+
/**
|
|
88
|
+
* Serialized account record persisted by the {@link StorageAdapter}.
|
|
89
|
+
*
|
|
90
|
+
* Survives reloads. Re-hydrates as **locked** — the account is present in
|
|
91
|
+
* `listAccounts()` and reachable via `getActiveAccount()`, but
|
|
92
|
+
* `getActiveSigner()` returns `null` until the user re-authenticates
|
|
93
|
+
* (passphrase for ncryptsec, page granted for extension, signer app for
|
|
94
|
+
* NIP-46/NIP-55).
|
|
95
|
+
*
|
|
96
|
+
* Method-specific fields:
|
|
97
|
+
* - `ncryptsec` — present when `method === 'ncryptsec'`. The encrypted nsec.
|
|
98
|
+
* - `nip46` — present when `method === 'nip46'`. URI, remote signer pubkey,
|
|
99
|
+
* relays, and the per-account client session keypair (hex). The client
|
|
100
|
+
* secret key is stored in plaintext on purpose — see the README's
|
|
101
|
+
* threat-model note.
|
|
102
|
+
* - `androidPackageName` — present when `method === 'android'`. Identifies
|
|
103
|
+
* which installed signer app fulfilled the login (e.g. Amber).
|
|
104
|
+
*/
|
|
105
|
+
interface StoredAccount {
|
|
106
|
+
npub: string;
|
|
107
|
+
pubkey: string;
|
|
108
|
+
method: LoginMethod;
|
|
109
|
+
ncryptsec?: string;
|
|
110
|
+
nip46?: {
|
|
111
|
+
uri: string;
|
|
112
|
+
remoteSignerPubkey: string;
|
|
113
|
+
relays: string[];
|
|
114
|
+
clientSecretKey: string;
|
|
115
|
+
};
|
|
116
|
+
androidPackageName?: string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The runtime signing surface exposed once an account is **unlocked**.
|
|
120
|
+
*
|
|
121
|
+
* Every concrete signer ({@link LocalSigner}, {@link ExtensionSigner},
|
|
122
|
+
* {@link BunkerSigner}, {@link AndroidSigner}) conforms to this. The
|
|
123
|
+
* abstraction has one deliberate omission: there is no `getPrivateKey()`.
|
|
124
|
+
* The raw secret key is never reachable through this interface — that is
|
|
125
|
+
* the package's central security invariant. Local signing holds the key
|
|
126
|
+
* in memory; the other methods sign remotely.
|
|
127
|
+
*
|
|
128
|
+
* `signEvent` accepts an unsigned {@link EventTemplate} (no `pubkey`,
|
|
129
|
+
* `id`, or `sig`) and returns a fully-signed {@link NostrEvent} —
|
|
130
|
+
* the implementation sets the `pubkey` to the active account's and fills
|
|
131
|
+
* in `id`/`sig`.
|
|
132
|
+
*
|
|
133
|
+
* `nip04Encrypt`/`nip44Encrypt` and their decrypt counterparts perform
|
|
134
|
+
* ECDH against `peerPubkey` (a 32-byte x-only hex pubkey). All four
|
|
135
|
+
* may throw if the remote signer (extension / bunker / Android) denies
|
|
136
|
+
* the operation.
|
|
137
|
+
*/
|
|
138
|
+
interface ActiveSigner {
|
|
139
|
+
getPublicKey(): Promise<string>;
|
|
140
|
+
signEvent(event: EventTemplate): Promise<Event>;
|
|
141
|
+
nip04Encrypt(peerPubkey: string, plaintext: string): Promise<string>;
|
|
142
|
+
nip04Decrypt(peerPubkey: string, ciphertext: string): Promise<string>;
|
|
143
|
+
nip44Encrypt(peerPubkey: string, plaintext: string): Promise<string>;
|
|
144
|
+
nip44Decrypt(peerPubkey: string, ciphertext: string): Promise<string>;
|
|
145
|
+
}
|
|
146
|
+
interface RelayMismatchInfo {
|
|
147
|
+
userRelays: string[];
|
|
148
|
+
bunkerRelays: string[];
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Called after pairing if the bunker's preferred relays (via get_relays)
|
|
152
|
+
* differ from the user-supplied list. Return `true` to accept the bunker's
|
|
153
|
+
* list — it will be stored on the account for future sessions. Return
|
|
154
|
+
* `false` (or anything falsy) to keep the user's list. Either way, the
|
|
155
|
+
* current in-memory session keeps using the user's relays since those
|
|
156
|
+
* just worked for pairing.
|
|
157
|
+
*/
|
|
158
|
+
type RelayMismatchHandler = (info: RelayMismatchInfo) => boolean | Promise<boolean>;
|
|
159
|
+
interface BunkerLoginOptions {
|
|
160
|
+
pool?: AbstractSimplePool;
|
|
161
|
+
onAuth?: (url: string) => void;
|
|
162
|
+
/** Reuse a stored client session keypair to resume a NIP-46 connection. */
|
|
163
|
+
clientSecretKey?: Uint8Array;
|
|
164
|
+
onRelayMismatch?: RelayMismatchHandler;
|
|
165
|
+
/**
|
|
166
|
+
* NIP-46 permissions to request as part of the `connect` call
|
|
167
|
+
* (e.g. `['sign_event:1', 'nip44_encrypt']`). Without this, many
|
|
168
|
+
* bunker UIs (e.g. Amber) show no approve/deny prompt because the
|
|
169
|
+
* connect request has nothing concrete to authorize.
|
|
170
|
+
*/
|
|
171
|
+
perms?: string[];
|
|
172
|
+
}
|
|
173
|
+
interface NostrConnectOptions {
|
|
174
|
+
relays: string[];
|
|
175
|
+
metadata?: {
|
|
176
|
+
name?: string;
|
|
177
|
+
url?: string;
|
|
178
|
+
image?: string;
|
|
179
|
+
};
|
|
180
|
+
perms?: string[];
|
|
181
|
+
/** Called once with the generated nostrconnect URI so the caller can render it. */
|
|
182
|
+
onUri: (uri: string) => void;
|
|
183
|
+
pool?: AbstractSimplePool;
|
|
184
|
+
onAuth?: (url: string) => void;
|
|
185
|
+
signal?: AbortSignal;
|
|
186
|
+
timeoutMs?: number;
|
|
187
|
+
onRelayMismatch?: RelayMismatchHandler;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Emitted by {@link Signer.onChange}. Variants:
|
|
191
|
+
* - `login` — a new account became active (no previous active account).
|
|
192
|
+
* - `switch` — the active account changed (including unlocking an already
|
|
193
|
+
* hydrated account, since unlock re-asserts the active signer).
|
|
194
|
+
* - `logout` — `logout(pubkey)` removed an account; emitted with the
|
|
195
|
+
* removed account's `pubkey` (the account itself is already gone from
|
|
196
|
+
* `listAccounts()` by the time the event fires).
|
|
197
|
+
*/
|
|
198
|
+
type SignerEvent = {
|
|
199
|
+
type: 'login';
|
|
200
|
+
account: StoredAccount;
|
|
201
|
+
} | {
|
|
202
|
+
type: 'logout';
|
|
203
|
+
pubkey: string;
|
|
204
|
+
} | {
|
|
205
|
+
type: 'switch';
|
|
206
|
+
account: StoredAccount;
|
|
207
|
+
};
|
|
208
|
+
interface SignerConfig {
|
|
209
|
+
/**
|
|
210
|
+
* Persistence backend. Defaults to a `localStorage`-backed adapter.
|
|
211
|
+
* Provide a custom adapter to use sessionStorage, an in-memory map,
|
|
212
|
+
* IndexedDB, or any other key/value store. See {@link StorageAdapter}.
|
|
213
|
+
*/
|
|
214
|
+
storage?: StorageAdapter;
|
|
215
|
+
/** Prefix applied to all keys written by the default localStorage adapter. */
|
|
216
|
+
storageKeyPrefix?: string;
|
|
217
|
+
/**
|
|
218
|
+
* Human-readable app name used as the default `name` metadata in
|
|
219
|
+
* the nostrconnect:// URI generated by `loginWithNostrConnect`.
|
|
220
|
+
* Remote signers (Amber, etc.) display this on the consent screen.
|
|
221
|
+
* Overridden by a per-call `metadata.name`.
|
|
222
|
+
*/
|
|
223
|
+
appName?: string;
|
|
224
|
+
/**
|
|
225
|
+
* Canonical app URL used as the default `url` metadata in the
|
|
226
|
+
* nostrconnect:// URI. Overridden by a per-call `metadata.url`.
|
|
227
|
+
*/
|
|
228
|
+
appUrl?: string;
|
|
229
|
+
/**
|
|
230
|
+
* Icon URL used as the default `image` metadata in the
|
|
231
|
+
* nostrconnect:// URI. Overridden by a per-call `metadata.image`.
|
|
232
|
+
*/
|
|
233
|
+
appImage?: string;
|
|
234
|
+
/**
|
|
235
|
+
* Default Android signer plugin (NIP-55). Provide the host app's
|
|
236
|
+
* `nostr-signer-capacitor-plugin` instance or an equivalent stub that
|
|
237
|
+
* satisfies {@link import('../nip55.js').AndroidSignerPlugin}.
|
|
238
|
+
* Can be overridden per-call via `loginWithAndroidSigner({ plugin })`
|
|
239
|
+
* or `listAndroidSignerApps(plugin)`.
|
|
240
|
+
*/
|
|
241
|
+
androidSignerPlugin?: AndroidSignerPlugin;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Multi-account Nostr signer with persistence.
|
|
246
|
+
*
|
|
247
|
+
* **Hydration.** The constructor reads previously-saved accounts from
|
|
248
|
+
* the configured storage adapter. Every hydrated account starts
|
|
249
|
+
* **locked**: present in `listAccounts()` and (if it was the active one
|
|
250
|
+
* before) reachable via `getActiveAccount()`, but `getActiveSigner()`
|
|
251
|
+
* returns `null` until the user re-authenticates. The matching
|
|
252
|
+
* `loginWith*` method unlocks the active account.
|
|
253
|
+
*
|
|
254
|
+
* **Locked vs unlocked.** Use `getActiveAccount()` to render UI ("logged
|
|
255
|
+
* in as @alice") and `getActiveSigner()` to decide whether the user can
|
|
256
|
+
* actually sign. The pattern is "show the account always, gate signing
|
|
257
|
+
* on the signer."
|
|
258
|
+
*
|
|
259
|
+
* **Events.** Subscribe via `onChange()` to re-render when an account
|
|
260
|
+
* is added, switched, or removed. See {@link SignerEvent}.
|
|
261
|
+
*/
|
|
262
|
+
declare class Signer {
|
|
263
|
+
#private;
|
|
264
|
+
constructor(config?: SignerConfig);
|
|
265
|
+
/**
|
|
266
|
+
* Generate a brand-new nsec, encrypt it with `passphrase` (NIP-49),
|
|
267
|
+
* persist the resulting `ncryptsec` account, and activate it. Returns
|
|
268
|
+
* the new account's `npub` and `ncryptsec` — the caller must surface
|
|
269
|
+
* the `ncryptsec` to the user **immediately** since it is the only way
|
|
270
|
+
* back into the account on a fresh device.
|
|
271
|
+
*
|
|
272
|
+
* @throws if `passphrase` is empty.
|
|
273
|
+
*/
|
|
274
|
+
createAccount(passphrase: string): Promise<{
|
|
275
|
+
npub: string;
|
|
276
|
+
ncryptsec: string;
|
|
277
|
+
}>;
|
|
278
|
+
/**
|
|
279
|
+
* Decrypt an ncryptsec with the user's passphrase, persist the account
|
|
280
|
+
* (overwriting any previous entry for the same pubkey), and activate it.
|
|
281
|
+
*
|
|
282
|
+
* @throws if either argument is empty, or if the passphrase doesn't
|
|
283
|
+
* decrypt the ncryptsec.
|
|
284
|
+
*/
|
|
285
|
+
loginWithNcryptsec(ncryptsec: string, passphrase: string): Promise<StoredAccount>;
|
|
286
|
+
/**
|
|
287
|
+
* Connect via the NIP-07 browser extension exposed at `window.nostr`.
|
|
288
|
+
* The extension prompts the user for permission on first use.
|
|
289
|
+
*
|
|
290
|
+
* @throws if no extension is installed or the user denies the request.
|
|
291
|
+
*/
|
|
292
|
+
loginWithExtension(): Promise<StoredAccount>;
|
|
293
|
+
/**
|
|
294
|
+
* Connect to a NIP-46 remote signer via a `bunker://` URI. Relays are
|
|
295
|
+
* read from the URI itself — no hardcoded fallbacks. Pass a `pool`
|
|
296
|
+
* to reuse an existing relay connection; pass `clientSecretKey` to
|
|
297
|
+
* resume a previous session (the hex from `StoredAccount.nip46`).
|
|
298
|
+
*
|
|
299
|
+
* @throws if the URI is malformed, no relay is reachable, or the
|
|
300
|
+
* remote signer rejects pairing within the implementation's timeout.
|
|
301
|
+
*/
|
|
302
|
+
loginWithBunkerUri(uri: string, options?: BunkerLoginOptions): Promise<StoredAccount>;
|
|
303
|
+
/**
|
|
304
|
+
* Initiate a NIP-46 `nostrconnect://` pairing. Generates a client
|
|
305
|
+
* keypair, publishes a connect request to the supplied `relays`, and
|
|
306
|
+
* waits for a remote signer to pair. Call `options.onUri(uri)` to
|
|
307
|
+
* render the URI as a QR code; the returned promise resolves once
|
|
308
|
+
* pairing completes. Cancel by aborting `options.signal`.
|
|
309
|
+
*
|
|
310
|
+
* @throws if `relays` is empty, the user aborts, the pairing times
|
|
311
|
+
* out, or no signer responds.
|
|
312
|
+
*/
|
|
313
|
+
loginWithNostrConnect(options: NostrConnectOptions): Promise<StoredAccount>;
|
|
314
|
+
/**
|
|
315
|
+
* Enumerate NIP-55 signer apps installed on the device, via the
|
|
316
|
+
* configured Android plugin (or `plugin` if supplied). Useful for
|
|
317
|
+
* rendering a "pick your signer" list — the built-in UI does this
|
|
318
|
+
* automatically when the Android tab is selected.
|
|
319
|
+
*
|
|
320
|
+
* Only meaningful inside a Capacitor Android shell. On web/iOS the
|
|
321
|
+
* configured plugin is typically absent and this throws.
|
|
322
|
+
*
|
|
323
|
+
* @throws if no plugin is configured and none is passed in.
|
|
324
|
+
*/
|
|
325
|
+
listAndroidSignerApps(plugin?: AndroidSignerPlugin): Promise<AndroidSignerAppInfo[]>;
|
|
326
|
+
/**
|
|
327
|
+
* Sign in via a NIP-55 Android external signer (Amber, etc). If
|
|
328
|
+
* `options.packageName` is given, that specific signer app is invoked;
|
|
329
|
+
* otherwise the plugin picks a default (typically the only installed
|
|
330
|
+
* signer, or an OS chooser). Pass `options.plugin` to override the
|
|
331
|
+
* configured default for this call.
|
|
332
|
+
*
|
|
333
|
+
* @throws if no plugin is configured, the signer app cannot be
|
|
334
|
+
* resolved to a package name, or the user denies the request.
|
|
335
|
+
*/
|
|
336
|
+
loginWithAndroidSigner(options?: AndroidLoginOptions): Promise<StoredAccount>;
|
|
337
|
+
/** Snapshot of every persisted account, in insertion order. */
|
|
338
|
+
listAccounts(): StoredAccount[];
|
|
339
|
+
/**
|
|
340
|
+
* The currently selected account, or `null` if none. Present even when
|
|
341
|
+
* the account is locked (no active signer yet). Use this to render
|
|
342
|
+
* "logged in as @alice" — pair with {@link getActiveSigner} to decide
|
|
343
|
+
* whether signing is actually available.
|
|
344
|
+
*/
|
|
345
|
+
getActiveAccount(): StoredAccount | null;
|
|
346
|
+
/**
|
|
347
|
+
* The unlocked signer for the active account, or `null` if locked.
|
|
348
|
+
* After a fresh page load this is `null` for every account type
|
|
349
|
+
* (passphrase / extension grant / signer-app handshake all need to
|
|
350
|
+
* be redone). Calling the matching `loginWith*` method unlocks it.
|
|
351
|
+
*/
|
|
352
|
+
getActiveSigner(): ActiveSigner | null;
|
|
353
|
+
/**
|
|
354
|
+
* Make `pubkey` the active account. Clears the in-memory signer —
|
|
355
|
+
* the new account starts **locked** even if it was previously
|
|
356
|
+
* unlocked in this session.
|
|
357
|
+
*
|
|
358
|
+
* @throws if `pubkey` does not match any persisted account.
|
|
359
|
+
*/
|
|
360
|
+
switchAccount(pubkey: string): Promise<void>;
|
|
361
|
+
/**
|
|
362
|
+
* Remove an account from storage. `pubkey` defaults to the active
|
|
363
|
+
* account. If the active account is removed, the in-memory signer is
|
|
364
|
+
* cleared. No-op if there is nothing to remove.
|
|
365
|
+
*/
|
|
366
|
+
logout(pubkey?: string): Promise<void>;
|
|
367
|
+
/**
|
|
368
|
+
* Subscribe to account-state changes. Returns an unsubscribe function.
|
|
369
|
+
* Listener errors are swallowed so one bad listener can't break others.
|
|
370
|
+
* See {@link SignerEvent} for the variants.
|
|
371
|
+
*/
|
|
372
|
+
onChange(cb: (event: SignerEvent) => void): () => void;
|
|
373
|
+
}
|
|
374
|
+
/** Convenience wrapper around `new Signer(config)`. */
|
|
375
|
+
declare function createSigner(config?: SignerConfig): Signer;
|
|
376
|
+
|
|
377
|
+
export { type ActiveSigner as A, type BunkerLoginOptions as B, type LoginMethod as L, type NostrConnectOptions as N, type RelayMismatchHandler as R, Signer as S, type AndroidLoginOptions as a, type AndroidLoginResult as b, AndroidSigner as c, type AndroidSignerAppInfo as d, type AndroidSignerPlugin as e, type RelayMismatchInfo as f, type SignerConfig as g, type SignerEvent as h, type StorageAdapter as i, type StoredAccount as j, createSigner as k, localStorageAdapter as l, loginWithAndroidSigner as m };
|