Amber
AGENTS.md368 starsChanged 12 days agoMITView on GitHub
These instructions apply to every coding agent working in this repository (Codex, OpenCode, Claude Code, …). CLAUDE.md only points here. Amber is a Nostr event signer (NIP-46 / NIP-55), package com.greenart7c3.nostrsigner. settings.gradle.kts includes five product modules — :app (Android), :desktop, :cli (a NIP-46 client for scripts and agents), :common, the logic the apps and the CLI share, and :commonsui, the string resources the apps share (see Modules) — plus three build-time tool modules, :unused-code, :architecture-tests and :detekt-rules.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository5 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- android-cliSkill
- ngitSkill
- android-cliSkill
- ngitSkill
The file
We split this AGENTS.md into the rules it gives an agent
11 rules. About 0 are common, 4 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
Run one test: ./gradlew :app:testFreeDebugUnitTest --tests "com.greenart7c3.nostrsigner.SomeTest" (or --tests "*SomeTest.method").
- Distinctive: line 35
When asked to "bump the version" / cut a release, do all the following in a single change — never omit the verification block:
- Distinctive: line 42
Start each bullet with a present-tense verb, name the concrete screen, setting or feature, and state the effect ("Show which account each …
- Distinctive: line 43
Leave out internal-only work (CI, refactors, tests, lint, build tooling) unless users can observe it.
- Very specific: line 45
CHANGELOG.mdmust contain only the latest release: delete the previous release's block from it (the notes already live in … - Very specific: line 48
Do not commit unless explicitly asked (per the global rule).
- Very specific: line 90
All three paths converge on Account.sign() / encrypt/decrypt methods backed by NostrSignerInternal.
- Very specific: line 105
Every npub gets its own:
- Very specific: line 111
All databases are lazy-loaded and cached in ConcurrentHashMaps in Amber.
- Distinctive: line 122
Before showing the approval UI, all three ingestion paths query the database.
- Very specific: line 131
When an auto-accept rule matches, all three paths sign silently without triggering the biometric/PIN prompt — including nostrsigner:// …
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Repository instructions for coding agents
These instructions apply to every coding agent working in this repository (Codex, OpenCode, Claude Code, …). CLAUDE.md only points here.
Amber is a Nostr event signer (NIP-46 / NIP-55), package com.greenart7c3.nostrsigner. settings.gradle.kts includes five product modules — :app (Android), :desktop, :cli (a NIP-46 client for scripts and agents), :common, the logic the apps and the CLI share, and :commonsui, the string resources the apps share (see Modules) — plus three build-time tool modules, :unused-code, :architecture-tests and :detekt-rules.
Toolchain
- JDK 21 required (source/target compat 21). CI uses Temurin 21.
compileSdk = 37,minSdk = 26, R8 full mode enabled, Gradle parallel + configuration-cache.- Room schemas are exported to
app/schemasvia KSP (room.schemaLocation). - Dependency verification is on:
gradle/verification-metadata.xmlpins the SHA-256 of every dependency and plugin artifact, and the build fails on any artifact that is missing or doesn't match. After adding or bumping a dependency or plugin, regenerate it with./gradlew --write-verification-metadata sha256 help <the tasks that use it>(e.g.assembleDebug test lintor:desktop:test :desktop:createDistributable) and review the diff. The per-OS Compose Desktop runtimes (desktop-jvm-*/skiko-awt-runtime-*for windows-x64, macos-arm64, macos-x64) andaapt2osx/windowsbuilds only resolve on their own OS, so bump their entries too, or desktop CI on Windows/macOS breaks.
Build and validation commands
./gradlew ktlintCheck— Kotlin style check (pre-commit hook runs this)../gradlew ktlintFormat— auto-fix formatting issues../gradlew detektAll— unused imports, parameters, variables and private declarations, plus the size/complexity rules, the Compose rules and Amber's own rules (config/detekt/detekt.yml,config/detekt/compose.yml,config/detekt/amber.yml), in the app (every flavor, unit and instrumented tests), desktop, cli, common, commonsui and the tool modules, with detekt's type resolution (pre-commit hook runs this). Every rule not listed in those files is off; suppress a deliberate one at its site with@Suppress("UnusedParameter")etc. Every module'sdetekt-baseline.xmlis empty: nothing is grandfathered, so a finding is fixed in the code (split the function or class, rename, or suppress a deliberate one at its site). Never add an entry by hand../gradlew detektBaselineAllregenerates the files from the current findings (the per-variant findings are merged into one file per module); a+line in its diff is a new violation that regenerating would grandfather, so fix the code instead of committing it. It also runs./gradlew unusedCode(tools/unused-code), which detekt cannot do because it sees one file at a time: across every module's sources it fails on a non-private function, property, class or typealias whose name nothing references (Kotlin sources including tests, XML, ProGuard rules, Gradle scripts andtools/arti/srcfor JNI callbacks), and on a catch parameter the block never reads (name it_). Overrides, operators,main, enum entries, constructor properties,@…Previewand test functions, and Room/serializer-read properties are never reported; mark code that only something outside the sources uses (reflection, the NDK) with@Suppress("unused").- Kotlin compiler warnings are errors (
allWarningsAsErrorsin the rootbuild.gradle.kts): deprecated APIs, needless?./!!/?:, unused expressions, unchecked casts, missing opt-ins. Fix them; when one is deliberate (e.g. the OkHttpbodynull checks the offline flavor's OkHttp 4 needs), suppress it at the statement. - No comments (
NoCommentsintools/detekt-rules, checked bydetektAllin every module): say it through names, types and structure instead of a comment. Allowed: KDoc on public or protected declarations of public classes (the API contract), a license header, tool directives (noinspection,ktlint-disable,@formatter:,language=) and links to an issue, an RFC or a NIP. A comment about a constraint outside our code (a platform, vendor or protocol quirk) goes under@Suppress("NoComments")on its declaration, so a reviewer sees the exception. A rule that only our own code carries (an ordering, a race, an invariant) is said through a name instead: extract the step into a function named after the rule (rebuildFiltersBeforeLeavingClearsThisScope,answerRevokedConnectionWithError) rather than suppressing the comment. After changing the rule, run./gradlew --stopfirst: the daemon keeps the old rule classes loaded. ./gradlew lint— Android Lint on the default variant;warningsAsErrorsis on, so any new warning fails the build (pre-commit and pre-push hooks run this). Version-freshness checks (GradleDependencyetc.) are disabled inapp/build.gradle.kts; per-path exemptions live inapp/lint.xml../gradlew test --no-daemon— JVM unit tests for all variants, including:architecture-tests(pre-push hook runs./gradlew test lint)../gradlew :architecture-tests:test— the architecture rules (Konsist)::common/:commonsuistay platform free,ui/does not import Room or call a DAO,Context.ambercannot spread to a new file,service//database/do not depend on Compose UI, the desktopcore/does not importui/, and application/permission rows are written only through the caching DAOs ofAccountRepository.daos(npub): onlyApplicationWriteDao,PermissionWriteDaoandPermissionMaintenanceDao(and Room migrations) write theapplication/applicationPermissiontables, each of their writes is overridden in itsCaching…wrapper with acache.invalidateApp/invalidateAll, and nothing outside that layer calls the uncached DAOs (AppDatabase.permissionWriteDao(),ApplicationDaos.of) or a*Rawwrite the wrappers pass through, and raw SQLite handles (openHelper,execSQL,@RawQuery,clearAllTables, …) appear only in Room migrations — otherwise the permission cache would keep serving revoked grants or an expired connection's lifetime. The allow-lists intools/architecture-tests/src/test/kotlin/.../ArchitectureTest.ktmay only shrink: the test fails when a listed file stops violating the rule, so delete the entry when you fix it. The target layering and the refactor roadmap are indocs/architecture.md../gradlew koverXmlReport koverHtmlReport— one merged coverage report for app, cli, common, commonsui and desktop inbuild/reports/kover(generated code excluded; not part ofcheck). Every one of those modules has a minimum line-coverage bound (minBoundin itsbuild.gradle.kts, set just below its measured coverage), enforced by:<module>:koverVerifyagainst the same classes the merged report counts (the rootbuild.gradle.ktsapplies its generated-code excludes to every module); raise a bound when coverage improves, never lower it. CI (build.yml, on Linux) runs the reports and everykoverVerifyafter the tests and uploads the HTML report.- Run one test:
./gradlew :app:testFreeDebugUnitTest --tests "com.greenart7c3.nostrsigner.SomeTest"(or--tests "*SomeTest.method"). ./gradlew assembleDebug --no-daemon— debug APK for both product flavors../gradlew assembleRelease --no-daemon— release APK; signing only activates when envSIGN_RELEASEis set andkeystore.propertiesexists. CI otherwisetouches an empty one../build.sh <version> <appName>— builds free + offline release APKs/AABs into~/release/and callsgenerate_manifest.sh.- Desktop:
./gradlew :desktop:run(debug build),:desktop:test,:desktop:packageDistributionForCurrentOs.
Required order when pushing: ktlintCheck → detektAll → lint → test → build (mirrored by the hooks, but run them directly; do not rely on hooks).
Releases / version bumps
When asked to "bump the version" / cut a release, do all the following in a single change — never omit the verification block:
- Bump
amberVersionCode(+1) andamberVersionName(newX.Y.Z) ingradle/libs.versions.toml. These are the only places the version lives: the AndroiddefaultConfigand the desktop app (:desktop, installers and the runtime-Damber.version) both read them, anddesktop-release.ymlfails if the tag does not matchamberVersionName. Never hard-code a version inapp/build.gradle.ktsor give the desktop its own. - Prepend a new
## Amber X.Y.Zblock at the top ofCHANGELOG.md, summarizing the non-merge commits since the previousvX.Y.Ztag (git log vX.Y.Z..HEAD --no-merges) as user-facing bullets, written the way previous "Bump version to …" commits wrote them — read one first (git log --oneline -- CHANGELOG.md, thengit show <commit> -- CHANGELOG.md). Releases up to 7.0.0-pre6 used one flat list; from now on, sort the bullets by product:- Group the bullets under
### Android,### Desktopand### CLI, in that order, and leave out a heading that has no bullets. Decide where a change goes by what it changes for users, not by its commit message. Check the files it touches (git show --stat <commit>):app/is Android,desktop/is Desktop,cli/is CLI. A change in:commonor:commonsuigoes under every app whose behavior it changes. - A change that users of more than one product see goes in each of those sections, with the same bullet repeated, so a reader who only uses one product finds everything that affects it. Do not add a "both"/"all platforms" section, and do not write "on Android and desktop" in a bullet once it is under a product heading.
- One bullet per user-facing change, ordered features → behavior changes → fixes → security hardening → dependency updates within each section. Never merge unrelated changes into one bullet, and never squeeze several changes into a single mega-bullet; only join closely related aspects of the same change with ", and".
- Start each bullet with a present-tense verb, name the concrete screen, setting or feature, and state the effect ("Show which account each batched request signs as", "Fix '+' in app names that clients form-encode in bunker URIs"). Prefix new features with
New:. - Leave out internal-only work (CI, refactors, tests, lint, build tooling) unless users can observe it; collapse dependency bumps into one closing line per section, listing only what that product ships ("Update Quartz to 2.3.0, OkHttp and the rest of the dependency stack").
End the block with the standard "Download it with …" line (update the
releases/tag/vX.Y.ZURL) and the "If you like my work …" donation line.CHANGELOG.mdmust contain only the latest release: delete the previous release's block from it (the notes already live indocs/changelogs/) and keep the## Older versionsfooter at the bottom. Also add the full notes asdocs/changelogs/<X.Y.Z>.md— same bullets and download/donation/verifying text, but under an# Amber X.Y.ZH1 and without the footer — and insert a row| X.Y.Z | [<X.Y.Z>.md](<X.Y.Z>.md) |at the top of the table indocs/changelogs/README.md(most recent first, padded to the existing columns; pre-releases get an entry too).
- Group the bullets under
- Always include the
## Verifying the releaseblock immediately after the donation line (before the next## Amberheading). Copy it verbatim from the previous release entry and only change themanifest-vX.Y.Z.txt/manifest-vX.Y.Z.txt.sigfilenames to the new version. Do not change thegpg --recv-keyskey id, thegpg: Signature made Fri 13 Sep 2024 …block, or the surrounding prose — those are key-specific, not release-specific. This block must be part of the version-bump commit, not a follow-up. - Do not commit unless explicitly asked (per the global rule). Do not edit
build.sh— it takes the version as an argument.
Product flavors (dimension version)
| Flavor | Notes |
free (default) | Online: OkHttp, Coil, built-in Tor (Arti, src/tor), relay connectivity. Owns INTERNET/network permissions. |
offline | No network stack. app/src/offline/AndroidManifest.xml removes INTERNET/CHANGE_NETWORK_STATE/ACCESS_NETWORK_STATE with tools:node="remove"; launcher name "Amber Offline". Keeps the online applicationId on purpose (as every offline APK released before 7.0.0 did), so installs from the releases page and Obtainium keep updating in place. |
offlinezapstore | The same offline app (shares the offline manifest and sources) with applicationIdSuffix=.offline, because Zapstore identifies an app by its applicationId and the "Amber Offline" listing (zapstore-offline.yaml) cannot publish APKs carrying the online one. CI builds it and keeps only the arm64-v8a APK (amber-offlinezapstore-arm64-v8a-<tag>.apk), which zapstore-offline.yaml matches. |
benchmark | Mirrors free network deps; applicationIdSuffix=.benchmark, versionNameSuffix=-BENCHMARK; CI builds a signed release per push for side-by-side install. |
- Guard any network-only code with
BuildFlavorChecker.isOfflineFlavor(). There is alsoBuildConfig.IS_FDROID_BUILD(false by default; the F-Droid release workflow flips it true and stripsREQUEST_INSTALL_PACKAGESviased) — read it throughBuildFlavorChecker.isFdroidBuild()to disable self-update / Zapstore, never as the constant, which the IDE would simplify away. - Offline permissions gate:
check-offline-permissions.ymlruns./gradlew processOfflineDebugManifest processOfflineZapstoreDebugManifestand greps both merged manifests for the three network permissions and the WorkManager components. Any new dependency that leaksINTERNETetc. will fail this check — verify the offline merged manifest when adding network-capable deps. Both offline flavors are the offline app:BuildFlavorChecker.isOfflineFlavor()is true forofflineandofflinezapstore, so gate network-only code through it, neverBuildConfig.FLAVOR == "offline".
Modules
:app— the Android app (everything in Architecture refers to it).:common— plain Kotlin/JVM library both apps depend on (packagecom.greenart7c3.nostrsigner.common) for logic that must behave the same on Android and desktop:SignerType/EncryptionType, the request policy (connectsThroughOtherKey,hasAmbiguousRelayTags,sanitizeAppName), the NIP-46 request basics (nip46SignerType,nip44v3SignerTypes,nip44v3Kind/nip44v3Scope/nip44v3Payloadand the v3 refusal messages,zapRequestParam(adecrypt_zap_eventis[pubkey, zap request], as Android reads it),hasRequiredParams(a request missing its method's params is refused withNIP46_INVALID_PARAMSbefore admission), the per-method param readers (peerPubKeyParam,encryptionTextParam,eventParam,psbtParam: read params through them, not by index),isRepeatedConnect,connectSecretRejectioninNip46Requests.kt), the requested-permission list a connect or nostrconnect URI carries (parseRequestedPermissions), the reply retry and attempt counts (retryWithBackoff,BUNKER_REPLY_ATTEMPTS,UNVERIFIED_REPLY_ATTEMPTSinRetry.kt: an error reply to an unverified sender is published once), the remembered-permission decision (activeDecision,rememberedDecision), the order grants are looked up in (permissionLookupOrder), how long a remembered choice lasts (rememberUntil), which stored grants a new one replaces (replacesGrant), the grants a sign policy gives and the grant remembering one decision (signPolicyGrants,rememberedGrant,Grant,contentScopedSignerTypesinGrants.kt), taking back an approval whose reply failed (revertedGrants,revertedConnectKey) and the types a requested permission is granted under (expandPermissionTypes), per-connection keys, who may be answered and what a request not admitted gets (admitNip46RequestandNip46Admission.replyinNip46Admission.kt: the reply, its relays and attempts), building and publishing a reply (nip46ReplyEvent,publishNip46Reply,ConnectionReplyKey/Nip46ReplyKey,nip46ReplyLoginNip46Replies.kt), what an admitted request does first (nip46StepinNip46Steps.kt:switch_relays,logout, the up-front refusals), crash-report redaction (CrashReports),Nip44v3,PsbtDecoder/PsbtSighashPolicy,RelayHealthTracker,SenderRateLimiter,TorSocksAuthenticatorandLocalRelayServer(the local bunker relay onws://127.0.0.1: the desktopLocalBunkerRelayand the AndroidLocalBunkerRelayServerare thin wrappers that supply its logger and approved senders; plain threads, since Android has no virtual threads). Put shared logic here instead of copying it into both apps; each app keeps only its storage, UI and platform glue around it. It has no Android or desktop APIs and compiles against Quartz withcompileOnly(quartz-jvm): each app ships its own Quartz build (quartz-android/quartz-jvm), so use only Quartz API both builds have. Its tests run with./gradlew :common:test(also part of./gradlew test).:commonsui— what both apps show, from one source: Kotlin Multiplatform (Android + JVM targets,com.android.kotlin.multiplatform.library) with every string as Compose Multiplatform resources insrc/commonMain/composeResources/values*/strings.xml, and thePermissionmodel (JSON form,kindsByNip/supportedKindNumbers, andPermission.description(), the one table mapping a permission type and event kind to its string, so a newevent_kind_*label is added there once). Strings exist only here: no AndroidR.stringcopy (the APK carries them once, as assets) — except the launcher labelapp_name*inapp/src/main/res/values/strings.xml, which the manifest needs as an Android resource. Both apps read them the same way through the generatedRes.string.<name>accessors (packagecom.greenart7c3.nostrsigner.commonsui, one import per accessor):stringResource(Res.string.x)(org.jetbrains.compose.resources, notandroidx.compose.ui.res) in composables, suspendgetStringin coroutines,getStringBlocking(commonsui/Strings.kt) in plain code; permissions withPermission.localized()/localizedBlocking(). Outside composition the language is the JVM default locale: Android sets it with the in-app language inAppLanguage.apply(AppCompat alone updates it only on Android 13+), the desktop inStrings.setLanguage. Folder names are whatLocale.language/countryreport: no region for a bare language (values-it, not-rIT) and Indonesian isvalues-id. Its tests run with./gradlew :commonsui:jvmTest; tests that read strings need Skiko, so they live in:desktop(StringsTest) and the app's instrumentedSharedStringsDeviceTest.:architecture-tests— Konsist tests (tools/architecture-tests) that enforce the layering above and run under./gradlew test. Its tests read the repository from disk, so Gradle cannot track their inputs (the task never goes up to date). Seedocs/architecture.md.:unused-code— the cross-module unused-code checker intools/unused-code, run bydetektAllas theunusedCodetask.:detekt-rules— Amber's own detekt rule set (amber, configured inconfig/detekt/amber.yml): the root build adds it to every other module's detekt plugins. Its tests (./gradlew :detekt-rules:test) check which comments the rule allows.:cli— theambercommand line client (packagecom.greenart7c3.nostrsigner.cli), for scripts, apps and AI agents that need a NIP-46 signature without speaking the protocol: pairing (loginwith abunker://URI,connectwith anostrconnect://URI/QR),sign-event,get-public-key, NIP-04/NIP-44 encrypt/decrypt,ping,status,logout, and an agent-orientedhelpplus stable exit codes (0 ok, 2 usage, 3 not paired, 4 refused, 5 timeout, 6 unreachable). It holds no accounts and no user keys: only throwaway per-connection client keys, saved in~/.config/amber-cli(%APPDATA%on Windows,AMBER_CLI_HOMEoverrides) inconnections.jsonencrypted with AES-256-GCM, the key living in the OS credential store (SecretStore: java-keyring, with a 0600 key-file fallback where none runs); never create a keyring entry from tests, passFileSecretStorethroughCliEnvironmentinstead.RelayPool/Nip46Clientare its own minimal relay client and protocol layer (com.greenart7c3.nostrsigner.commonforLocalRelayServerconstants,decodeQueryParamValueandRELAY_AUTH_KIND); default relays mirrordefaultAppRelaysin the app andDesktopSettings.defaultRelays. Its docs arecli/README.md;./gradlew :cli:testruns the unit and end-to-end tests (a local relay plus a fake signer, no network),:cli:packageClibuilds the self-containedjpackagearchive that.github/workflows/cli.ymlships on every OS.:desktop— Compose for Desktop (JVM) NIP-46 signer for Windows/macOS/Linux; standalone port that mirrors the Android permission model againstquartz-jvm(no NIP-55)../gradlew :desktop:runlaunches a debug build (core/BuildVariant.kt: separate data dir, keyring entry, socket and "Amber Debug" name, so it never touches a release install).- Bunker engine: its core mirrors
NotificationSubscription/EventNotificationConsumer/BunkerRequestUtilsindesktop/.../core/BunkerEngine.kt— behavior changes to the Android bunker flow should be ported there too. - Keys: AES-encrypted (
DesktopKeyStore) with a master key from a PKCS12 Java KeyStore (DesktopMasterKey, which owns the key's lifecycle) whose password lives in the OS credential store (Keychain / Credential Manager / Secret Service viajava-keyring, file fallback — seeKeystorePassword.resolve). That keystore only exists before first run: the passphrase is mandatory (PassphraseLock, setup screen before anything loads), and setting it wraps the master key with Argon2id — combined via HKDF with a random secret in the OS credential store when one works (osSecretStore, a second factor) — and deletes the keystore. It adds a startup/auto-lock gate that evicts key material and gates the bunker engine, and encrypts the per-account database (apps/permissions/history/logs) at rest viawriteSecure/readSecure. Every master-key ciphertext is context-bound (GCM AAD,DesktopKeyStore.encryptString(…, context)), and while a passphrase is set unbound or plaintext data is rejected.applications.jsonis also rollback-protected: its header carries a generation (AMBERENC3:<n>:, bound into the AAD) whose latest value is kept in the OS credential store (StoreGenerations), and an older copy is refused. The desktop app has no released predecessor, so there are no migrations: only the current formats are read, and anything else is treated as tampered. Write files withAppDirs.writeAtomically; unreadable files are quarantined, never overwritten. Lock wipes key material (WipeableAesKey,DesktopAccount.wipe, Quartz NIP-04/44 caches): keep secrets inByteArrays (decryptBytes), not Strings, and don't hand out an account outsideAmberDesktop.account(only cached accounts get wiped). State is JSON files per account (no Room). - Local socket signer: an always-on NIP-5F local socket signer (
core/LocalSigner.kt+LocalSignerProtocol.kt,~/.local/share/nostr/signer.sock) feeds CLI tools through the sameBunkerEnginepermission/approval pipeline as NIP-46: socket apps areAppRecords withtransport = "socket"and no relays, and their pending requests carry aresponderthat answers over the socket instead of a kind-24133 event. Protocol and internals:desktop/LOCAL_SIGNER.md. - Notifications: they go through the OS-native channel (
core/Notifier.kt: freedesktopnotify-send/gdbuson Linux incl. Wayland/Hyprland; AWT tray notification on Windows and macOS — neverosascripton macOS, it posts as Script Editor, which is never authorized, and is silently dropped), decoupled from the tray. Request notifications carry Approve / Reject (Reject only for connect): on Linux daemons that draw action buttons they are posted over the session D-Bus with dbus-java (core/DbusNotifications.kt— the daemon sendsActionInvokedonly to the posting connection, and notify-send 0.8.8 drops the buttons on GNOME 50); on Windows as a WinRT toast (core/WindowsToasts.kt, JNA: Amber registers its own AppUserModelID under HKCU and gets clicks through the toast's in-processActivatedevent — no COM activator or URL scheme, so nothing outside the process can answer a request); on macOS throughUNUserNotificationCenter(core/MacNotifications.kt, JNA over the Objective-C runtime, buttons as notification categories, shown under the banner's "Options"). macOS only accepts that from a code-signed bundle (ad-hoc is enough; an unsigned one makesusernotificationsdlog "requestAuthorization not allowed"): jpackage signs ad hoc on Apple silicon only, soMacAdHocSignatureindesktop/build.gradle.ktssigns the Intel app increateDistributable, which the DMG is made from;:desktop:runhas no bundle and is not authorized. Where the native channel cannot show buttons — button-less Linux daemons (mako, dunst, other quickshell configs), a macOS app the user has not allowed to notify, or a post that failed — Amber shows its own native-looking popup (ui/RequestNotificationPopup.kt). Request notifications are skipped while the main window is focused (the card is already in view), and focusing it closes a showing popup. Answering a request — on its card, in the tray window, or from the notification itself — withdraws its notification (Notifier.Notification.close:CloseNotificationon the posting D-Bus connection, or by id afternotify-send --print-idin the fallback;Hideon Windows;removeDeliveredNotificationson macOS), and Amber's own popup closes itself the same way once its request leaves the queue. Omarchy's shell keeps a card its sender closed (only the buttons go), so there the card is also dismissed through the shell's IPC by title (Notifier.omarchyDismissCommands; a substring match, so titles under 3 characters are left alone). Notifications still open when Amber quits are closed by a shutdown hook, and macOS clears what a killed run left behind at the next start. On Linux the popup is a POPUPJWindow(override-redirect on X11), not a ComposeWindow/JFrame; AWT's peer still types it NORMAL on XWayland, which Hyprland focuses on map, somarkAsX11Popupsets the peer'swindowTypeby reflection (needs the--add-opens=java.desktop/sun.awt.X11JVM arg) — never let the popup take keyboard focus. The packaged runtime needs thejdk.security.authmodule for dbus-java's bus login, which also enables the Secret Service keyring path, andjdk.netfor the local socket signer's peer check. jlink only bundles the modules listed innativeDistributions { modules(...) }plus what the plugin detects, and:desktop:runuses the full JDK, so a missing module only fails in the packaged app: check new JDK-module imports withjdepsonlib/app/*.jarofcreateDistributable. Focusing the main window closes Amber's own popup, except while the pointer is on it: on macOS clicking the popup activates the app and focuses the main window before the click lands, which used to swallow Approve. - Crash reports:
core/CrashReporter.ktmirrors the AndroidUnexpectedCrashSaver/ReportAssembler/ReportSender(redactedcrash.trace, NIP-17 DM toDEVELOPER_HEX_KEYon user consent,ui/CrashReportDialog.ktafter unlock); the version comes from the launcher's-Damber.version(BuildVariant.version), i.e.amberVersionName. - Tray: the dorkbox SystemTray library on Linux (
NativeTray.kt) publishes a StatusNotifierItem/AppIndicator that shows on Wayland compositors; Windows/macOS use the AWT/ComposeTray.AMBER_DISABLE_TRAY=1skips the native tray. - See
desktop/README.md.
- Bunker engine: its core mirrors
Architecture (Android app)
Request ingestion — three paths
External apps and relays reach the signer through three distinct paths:
nostrsigner:///nostrconnect://Intent →SignerActivity→ parsed byIntentUtils→ shown as an approval bottom sheet- ContentProvider IPC →
SignerProvider→ synchronous signing viarunBlocking - NIP-46 relay events (kind 24133) →
NotificationSubscription→EventNotificationConsumer→BunkerRequestUtils
All three paths converge on Account.sign() / encrypt/decrypt methods backed by NostrSignerInternal.
Global state — Amber.kt
Amber is the Application class and acts as the DI container. There is no static accessor: it implements SettingsStore and holds accountDatabases (the AccountRepository) and relayClient (the RelayClient, data/), which code takes through constructors or parameters; Android entry points read the container from their context (Context.amber) and composables from the CompositionLocals in ui/AppDependencies.kt. Key singletons it owns:
applicationIOScope—CoroutineScope(Dispatchers.IO + SupervisorJob() + exceptionHandler), used for all background workrelayClient: AppRelayClient— theRelayClient: the Quartz Nostr relay client (relayClient.client), its WebSocket factory, the relay stats and the reconnect logicnotificationSubscription— keeps the NIP-46 filter alive in the backgroundprofileSubscription— per-account, throttled one-shot metadata fetch; first fetches the user's NIP-65 relay list (kind 10002) and saves it locally, then fetches the metadata (kind 0) from the default profile relays plus the saved user relays; started/stopped by the composables that display each account viaProfileSubscriptionEffect(not app-wide)isStartingAppState: MutableStateFlow<Boolean>— set totrueduringrunMigrations(); code that must wait for startup callsisStartingAppState.first { !it }settings.killSwitch— when true, all relays are disconnected; checked before every relay operation
Per-account isolation
Every npub gets its own:
SharedPreferencesfile (prefs_${npub})AppDatabase(amber_db_${npub}) — apps + permissionsLogDatabase— operation logsHistoryDatabase— request history
All databases are lazy-loaded and cached in ConcurrentHashMaps in Amber. Account data (including decrypted keys) is loaded via AccountStorage.load() and cached in LargeCache.
Permission system
Permissions are stored in ApplicationEntity + ApplicationPermissionsEntity (Room). Each permission entry has:
rememberType— auto-accept, auto-reject, or always-askacceptUntil/rejectUntil— time-bound grantskind— event-kind-specific rules
NIP-44 v3 grants are keyed by the context kind only (a kind-K rule, or a kind-less "all kinds" rule); the context scope string (params[2]) is shown in the approval prompt but is not stored, so a remembered kind-K grant covers every scope. Desktop (BunkerEngine, LocalSigner) follows the same model; keep them in step if that ever changes.
Before showing the approval UI, all three ingestion paths query the database; if a matching auto-accept rule exists, signing proceeds silently.
Biometric / PIN lock is UI-only
The biometric/PIN prompt (useAuth / usePin in AmberSettings, configured in SecurityScreen) is only an app-launch UI gate, not a signing gate. It is rendered by BiometricAuthScreen, which is invoked exclusively from the two UI entry points — MainActivity and SignerActivity — to unlock the app's screens before any approval bottom sheet is shown.
It does not protect the signing operations themselves:
- ContentProvider IPC (
SignerProvider) and NIP-46 relay events (EventNotificationConsumer→BunkerRequestUtils) never touchBiometricAuthScreen,Biometrics,useAuth, orusePin. They sign in the background based purely on the permission database. - When an auto-accept rule matches, all three paths sign silently without triggering the biometric/PIN prompt — including
nostrsigner://intents, which auto-finish before the UI is interacted with.
In other words, the lock controls who can open and navigate the app UI; it does not stand between a request and Account.sign(). Authorization for automatic signing is governed solely by the permission system (rememberType / acceptUntil / kind). Do not wire signing through the biometric prompt.
The requireUnlockedDevice opt-in is a signing gate
Separate from the UI-only lock above, the user can enable requireUnlockedDevice (SecurityScreen). When enabled, every Account private-key operation (sign, signSync, signPsbt, decryptZapEvent on Account; nip04*/nip44*/nip44v3* and decrypt on account.crypto (AccountCrypto); getNsec, seedWords, nip49Encrypt on account.keyExport (AccountKeyExport); and the backup derived signer) calls KeystorePolicy.requireAccess (through Account.requirePrivateKeyAccess; a new private-key operation must do the same) (over DeviceUnlockPolicy.requireAccess) first and throws SecurityException while the device is locked. The flag is read synchronously from SharedPreferences (KeystorePolicy.requireUnlockedDevice), so the gate is correct even before the async settings load and in the offline flavor.
Consequences to keep in mind when touching these paths:
- Background consumers of gated operations must handle the refusal explicitly: the relay AUTH coordinator isolates per-account failures,
BackupApplicationsWorkerreturnsResult.retry()on the lock refusal, and lock/settings refusals are rethrown (not swallowed) byvalidateNip44v3RequestandApplicationBackupPayloads.decryptContentso clients and callers see the real condition instead of a decrypt/corruption error. - NIP-46 requests are checked before they are opened: while locked,
EventNotificationConsumeranswers clients that have their own connection key with a "locked" error (using only that key), and leaves requests from legacy clients, which are encrypted to the account key, unopened and unrecorded so a re-delivery after unlock is processed. - This gate is independent of the biometric/PIN UI lock: with
requireUnlockedDevice=false(the default), background signing behaves exactly as described above.
Key files
| File | Purpose |
Amber.kt | Application singleton, Nostr client, relay connectivity |
LocalPreferences.kt | Account/settings persistence, encrypted key storage |
IntentUtils.kt | Parses nostrsigner:// URIs, creates IntentData objects |
SignerProvider.kt | ContentProvider IPC signing |
BunkerRequestUtils.kt | NIP-46 protocol handling, relay responses |
AccountStateViewModel.kt | Auth state, account switching, toast notifications |
ConnectivityService.kt | Foreground service, network monitoring, relay reconnection |
BiometricAuthScreen.kt | UI-only app-launch lock (biometric/PIN); not a signing gate |
Biometrics.kt | Wraps BiometricPrompt / keyguard credential prompt |
SecurityScreen.kt | Toggles useAuth / usePin and the re-prompt interval |
Conventions
- ktlint
android_studiocode style (.editorconfig); star imports effectively disabled; trailing commas allowed;@Composablefunctions exempt from the function-naming rule. RunktlintFormatrather than hand-formatting. - Translations live in
commonsui/src/commonMain/composeResources/values-<locale>/strings.xml(Compose resources, shared by the Android and desktop apps). Android lint does not check them (they are not Android resources), so nothing flags a missing or broken translation. The text is plain: no Android string syntax — write apostrophes, quotes,%and line breaks literally (no\',\n,%%or"…"quoting), and use positional%1$s/%1$dfor arguments (Compose resources substitute nothing else). XML entities (&,<) are still needed. - Strings must be translated in the same change. Whenever you add or change a string in
commonsui/src/commonMain/composeResources/values/strings.xml— includingevent_kind_*labels for new Nostr kinds — add the real translation to everycommonsui/src/commonMain/composeResources/values-*/strings.xmllocale file (ls commonsui/src/commonMain/composeResources) before reporting the work as done. Never stop at English and never copy English into a locale file — write the actual translation, matching the existing tone/register of that file. A passing build does not mean the translations are present. - Git hooks (
git-hooks/pre-commit,pre-push) are auto-installed by the rootbuild.gradle.ktsinstallGitHooktask wired into:apppreBuild— no manual setup needed, but do not rely on them as a substitute for running checks directly.
Reproducibility
Dockerfile + apkdiff.py verify reproducible builds: docker build -t amber-repro --build-arg VERSION=vX.Y.Z --build-arg APK_TYPE=free-arm64-v8a . then docker run --rm amber-repro (expect APKs match!).
Desktop: every download is reproducible by content, checked with desktopdiff.py (files plus installer scripts/tables; timestamps and build dates ignored; --jdk prints the bundled JDK). Dockerfile.desktop rebuilds the Linux .tar.xz, AppImage, .deb and .rpm of a tag and compares them with the release; Windows (.msi/.exe) and macOS (.dmg) are rebuilt on that OS (README has the steps). What keeps it that way: desktop.yml makes setup-java download the official Temurin archive (an empty RUNNER_TOOL_CACHE), since the app bundles that JDK's runtime and the runner's preinstalled copy differs; SkikoNatives in desktop/build.gradle.kts ships skiko's native library as plain files instead of the skiko-awt-runtime jar, which Compose 1.12 rewrites with the build time (Compose 1.13 fixes that), and ZipTimestamps fixes the entry times of the jars the plugin re-zips on macOS; .gitattributes turns off line-ending conversion, which made Windows checkouts bundle CRLF resources. Run python -m unittest discover -s tests after changing desktopdiff.py.
Collaboration
For repository collaboration, use ngit and follow .agents/skills/ngit/SKILL.md (mirrored at .claude/skills/ngit/SKILL.md).
Android CLI
For building, installing and driving the app on a device or emulator, screenshots, UI inspection, Compose preview renders and Android docs, follow .agents/skills/android-cli/SKILL.md (mirrored at .claude/skills/android-cli/SKILL.md).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

