auth-signers

vitorpamplona/amethyst

Паттерны подписи событий в Amethyst: локальный, NIP-46 и NIP-55 signer.

Звёзды1 624
Авторvitorpamplona

Установка

SKILL.md

Auth & Signers

Any time Amethyst produces a signed Nostr event, it goes through a NostrSigner. There are three kinds; all three implement the same abstract contract so feature code doesn't care which one the user has configured.

When to Use This Skill

  • Adding a new flow that publishes an event (follow, post, react, zap, profile edit).
  • Reviewing whether a feature works when the user has a remote bunker signer or an external Android signer.
  • Debugging "Sign request approved but nothing happens" / timeouts on sign operations.
  • Onboarding a new signer kind (hardware signer, browser extension, etc.).
  • Understanding the NIP-46 bunker request/response taxonomy.

The Abstract Contract

quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip01Core/signers/NostrSigner.kt:

abstract class NostrSigner(val pubKey: HexKey) {
    abstract fun <T : Event> sign(
        template: EventTemplate<T>,
        onReady: (T) -> Unit,
    )
    abstract fun nip04Encrypt(plaintext: String, toPubKey: HexKey, onReady: (String) -> Unit)
    abstract fun nip04Decrypt(ciphertext: String, fromPubKey: HexKey, onReady: (String) -> Unit)
    abstract fun nip44Encrypt(...)
    abstract fun nip44Decrypt(...)
    abstract fun decryptZapEvent(event: LnZapRequestEvent, onReady: (LnZapRequestEvent) -> Unit)
}

Sibling files in the same folder:

  • NostrSignerInternal.kt — in-process signer with the user's seckey in memory. Fastest; used for locally-stored accounts.
  • NostrSignerSync.kt — blocking wrapper for scripts / migrations / tests where callbacks are inconvenient.
  • EventTemplate.kt — the unsigned holder passed to sign().
  • SignerExceptions.kt — the error taxonomy (user denied, timeout, unsupported method, etc.).
  • caches/ — request cache so duplicate sign/encrypt requests coalesce.

Concrete implementations

  • Local (in-process): NostrSignerInternal — direct Secp256k1Instance.signSchnorr + NIP-44 inline. Used by accounts created/imported into Amethyst.
  • Remote (NIP-46 bunker): quartz/.../nip46RemoteSigner/signer/NostrSignerRemote.kt. Talks to a bunker service over Nostr DMs using the BunkerRequest* / BunkerResponse* event taxonomy (BunkerRequestConnect, BunkerRequestSign, BunkerRequestNip44Encrypt, …).
  • Android external (NIP-55): quartz/src/androidMain/.../nip55AndroidSigner/client/NostrSignerExternal.kt. Uses Android intents + content provider to delegate to another app on the same device. Launcher: ExternalSignerLogin.kt, IActivityLauncher.kt. Install-check: IsExternalSignerInstalled.kt.

The SignerResult Contract

Signers return via callback (and internally track via SignerResult sealed types in nip46RemoteSigner/signer/SignerResult.kt and nip55AndroidSigner/api/SignerResult.kt). Result variants cover success, user-denied, timeout, remote-disconnected, unsupported. Feature code should:

  1. Pass a callback that handles success.
  2. Trust the cache/timeout behavior — don't roll your own retry.
  3. Surface SignerExceptions to the user with actionable messaging (e.g. "Bunker disconnected — reconnect?").

Typical Flow (Feature Code)

// High-level: Account methods already do this internally.
val signer: NostrSigner = account.signer     // whichever kind the user configured

val template = reactionEventTemplate(noteId, authorPubKey, "+")

signer.sign(template) { signed ->
    account.sendToRelays(signed)             // or similar pipeline
}

Most feature code should go through Account's mutation methods (account.sendReaction, account.follow) rather than touching the signer directly — the account layer handles signing + publishing + local state update atomically. Reach for the signer directly only when Account doesn't have a helper.

Choosing a Signer at Sign-Up

Entry points:

  • Existing private key (nsec, 32-byte hex, file) → NostrSignerInternal.
  • Bunker URL (bunker://...) → NostrSignerRemote.fromBunkerUri(bunkerUri, localSigner, client) in nip46RemoteSigner/signer/NostrSignerRemote.kt parses the URI and returns a NostrSignerRemote; then call its suspend fun connect() to perform the NIP-46 handshake.
  • Installed external signer app (Amber, nos2x, etc. on Android) → ExternalSignerLogin.launch(...) opens the signer app; approval yields a NostrSignerExternal.

The UI hosts both flows via amethyst/.../ui/screen/loggedOff/login/ — look there for ExternalSignerButton.kt and the bunker-URL paste screen.

Trade-offs

SignerLatencyOffline OK?SecurityUX
InternalµsYesKey in app memoryNo confirmation prompts
Remote (NIP-46)100ms–secondsNo (needs bunker reachable)Key never touches AmethystOccasional approval prompts
External (NIP-55)100–500msYesKey in separate appPrompt on every sign by default (configurable)

Gotchas

  • Callbacks may never fire. External signers can be dismissed without result; remote signers can time out. Use SignerExceptions / timeout handling at every call site or rely on the Account layer's wrapping.
  • nip04Encrypt is legacy for NIP-04 DMs. New DM code should use NIP-17 gift-wrap → nip44Encrypt path.
  • Don't cache signer output beyond the caches/ that quartz already maintains. Stale cache entries lead to duplicate publishes.
  • Remote signer disconnects need explicit reconnection UX — RemoteSignerManager exposes state; hook into it for an account-switching warning.
  • External signer launch requires an Activity context — it can't happen from a background service. Structure flows so signing is on the main dispatcher through an activity-scoped launcher.
  • NostrSignerSync is rare. If you reach for it, you're probably in a test or migration — production code uses the async API.

References

  • references/nip46-remote-signer.md — the NIP-46 bunker message taxonomy and connection lifecycle.
  • references/nip55-android-signer.md — Android intent-based external signer flow.
  • Complements: nostr-expert/references/crypto-and-encryption.md (the crypto under all signers), account-state (which wraps signer calls), android-expert (intent launcher patterns).

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: auth-signers](https://darkplay.ru/ai/skills/vitorpamplona-amethyst-auth-signers)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Security Revieweraffaan-m · Ищет и устраняет уязвимости: секреты, SSRF, инъекции, крипто и OWASP Top 10.
225 587 ★
agentic-bundle-skill-authorsickn33 · Установите набор редакционных навыков "Skill Author" для Claude Code.
49 917 ★
agentforce-adlcanthropics · Жизненный цикл разработки агентов Agentforce — создание, поиск, скаффолдинг…
100 комп.
amazon-location-serviceanthropics · Помогает разработчикам добавлять карты, поиск мест, геокодирование, маршрутизацию и…
100 комп.
astronomer-data-agentsanthropics · Инженерия данных для Apache Airflow и Astronomer: написание DAG по лучшим практикам…
100 комп.
auth0anthropics · Корпоративная аутентификация, простая во внедрении. Добавляйте вход, SSO, MFA и контроль…
100 комп.
aws-amplifyanthropics · Создание full-stack приложений на AWS Amplify Gen 2 с пошаговыми сценариями для…
100 комп.
aws-coreanthropics · Создание, развёртывание и эксплуатация приложений на AWS. Навыки написания…
100 комп.
convexanthropics · Официальный плагин Convex для Claude Code с набором навыков Convex, субагентом…
100 комп.
dataanthropics · Инженерия данных для Apache Airflow и Astronomer. Создание DAG по лучшим практикам…
100 комп.

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8