The ubuntu-latest runner image ships GTK 4.22, which cannot satisfy the crate's v4_24/v1_10 features (they want GTK >= 4.23 / libadwaita >= 1.10, newer than the latest stable GNOME release), so the first CI run failed compiling gdk4-sys. The GNOME OS SDK is no better. Build a regent-ci image (build-aux/ci/) from Arch with the GTK/libadwaita headers, a rustup-pinned toolchain and the static cargo-deny binary baked in, register a repo-level runner with the matching label, and drop the apt/rustup/install-action steps. Bump url to 2.5.9 (RUSTSEC-2026-0592), which the cargo-deny step would otherwise fail on.
98 KiB
Regent — notes for agents and contributors
A Nostr remote signer (NIP‑46) for GNOME. Rust + gtk4/libadwaita, Meson,
Blueprint, GResource, GSettings. Development happens on nuc in
~/src/regent; repo https://gitea.kosmos.org/raucao/regent (canonical —
mirrored on Nostr, see below).
The full plan lives at ~/.opencode/plan/regent.md.
Hard rules
-
Unlicense (public domain) for all code. No copyright headers needed. Don't add a license header to new files. The name and logo are trademarks, separate from the code license — see
TRADEMARK.md; keep branding claims and that policy in step. -
The NIP‑46 responder is ours. Do not add a NIP‑46 signer/bunker dependency, and do not shell out to
nak.nakis a test instrument only. -
No Flatpak. Distribution is AUR + Gitea releases + Nostr events.
-
Gitea is canonical, Nostr is a mirror.
originishttps://gitea.kosmos.org/raucao/regent.gitand every branch tracks it; the NIP-34 announcement advertises it as both the homepage and a clone URL. The repo is announced on Nostr throughngit:git push nostr mainpublishes a branch there, under remotenostr/nostr.repo. The announcement's coordinate isnaddr1qqr8yet8v4h8gq3qraustrrh5gjwt03zdj8syn9vmt2dwsv9t467m8c3gua636uxu89sxpqqqpmejc3094cRepo events go only to the two repo relays (
wss://nostr.kosmos.org,wss://relay.ditto.pub—nostr.repo-relay-only=trueis global). Pushing there copies the git data to the GRASP hosts (relay.ngit.dev,gitnostr.com) as well, so a branch pushed to Nostr is publicly clonable without Gitea; deleting the announcement only unlists it. Metadata is edited withngit repo edit(--add-additional-relay, …). Note a freshngit initrenames the Gitea remote togitea-kosmosand pointsoriginat Nostr: rename them back sooriginstays Gitea. -
Never write an identity
nsecto disk in the clear. Identity keys are NIP-49 (ncryptsec) inkeys.json, mode 0600, under one passphrase. The device key is the one deliberate exception — plaintext in the same file (see "The key vault (M8)"). Nothing else is. -
Split keys:
device(NIP‑46 transport + response signing, rotatable) anduser(the nsec — signs events, nip04/44 only). The user key must never be used for relay traffic.
Layout
src/main.rs arg parsing, resource registration, entry point
src/application.rs AdwApplication, actions, CSS
src/headless.rs headless mode + CLI pairing (no window)
src/window.rs the windows: main, identities, and the registry (M10)
src/config.rs GSettings wrapper (+ REGENT_RELAYS override)
src/runtime.rs tokio runtime + the bridge back to the GTK main loop
src/runner.rs the signer's lifecycle + the approval drain (process-wide)
src/state.rs shared state: key vault, app registry, activity log, change channel
src/signer/mod.rs the NIP-46 responder
src/signer/approval.rs asking the user (timeout ⇒ deny), incl. unlocking
src/signer/policy.rs the auto-approval rate limit
src/store/apps.rs the registry of approved applications + their permissions
src/store/audit.rs the activity log (metadata only, mode 0600)
src/store/keys.rs the NIP-49 key vault (identity keys + the device key)
src/store/profiles.rs cached kind-0 names and picture URLs (read-only)
src/store/icons.rs app icons + identity avatars: hardened fetch, disk cache (M11)
src/store/nip05.rs NIP-05 parse + the verified-address check (single HTTP path)
src/ui/approval.rs approval dialogs
src/ui/apps_view.rs the apps page (permission table + revoke)
src/ui/activity_view.rs the activity page
src/ui/connect.rs the "Connect an app" dialog (pairing + QR reveal)
src/ui/kind.rs human names for the common event kinds
src/ui/plain.rs plain-text rows/dialogs (markup off)
src/ui/preferences.rs the preferences dialog (vault + rate limit)
src/ui/keys_view.rs the identities window's content (list + management)
src/ui/switcher.rs the header identity switcher
src/ui/qr.rs QR → GdkTexture
data/ desktop, metainfo, gschema (all `.in` templates), icons, resources (ui/*.blp, style.css)
The signer (NIP-46)
- Requests arrive as
kind:24133events p-tagged to the device key. The responder decrypts (NIP-44 first, NIP-04 as a legacy fallback), parses the{id, method, params}envelope by hand — rust-nostr's typed NIP-46 request cannot represent a spec-shapedsign_event— and answers NIP-44 encrypted, p-tagging the client, signed with the device key. - Methods:
connect(verifies the pairing secret),get_public_key,get_relays,switch_relays,ping,sign_event,nip04/nip44_encrypt|decrypt. - Approved ≠ silent (M4). A client that is not in the registry gets no answer
to anything except
connect— the request is dropped silently (Ok(None), no reply, no log), and aconnectwith a wrong or absent secret is dropped the same way, so a stranger cannot use error replies as a presence oracle. An approved client is remembered inapps.jsonbut every sensitive request is still put to the user:sign_event,nip04/nip44_encryptandnip04/nip44_decrypt.get_public_key,get_relays,switch_relaysandpingstay automatic. - Bounded-concurrency dispatch (M8). The responder handles requests
concurrently, up to
DISPATCH_PERMITS(16) at a time, so a prompt that waits out the approval deadline cannot stallping,get_public_keyor an auto-approved signature behind it. TheApprover's drain still serializes the interactive dialogs themselves, so two prompts are never on screen at once. - Policy model. A dialog answers Deny / Allow once / Allow always. "Always"
stores a
Permissionon the app inapps.json: forsign_eventan allow-list of kinds, for encryption a method name. A request covered by a stored permission is answered without asking — subject to the rate limit below. - Decryption always asks. It is a content oracle, so
Decryptnever stores a permission and the dialog offers only Deny / Allow once. Silently decrypting is the exact flaw this project exists to replace; do not "optimise" it away. - NIP-04 is flagged (I2). A
nip04_encrypt/nip04_decryptrequest adds an above-the-fold banner saying NIP-04 is the older, unauthenticated scheme and NIP-44 is recommended (request_warnings, comparing thenim_nameform"nip04"). - Rate limit.
signer::policy::RateLimitercaps silent answers per app:auto-approve-limitrequests per minute (GSettings, default 30). Past the cap the request is asked again, so a runaway or compromised client turns back into prompts instead of an open tap. Zero means never answer silently. The limit is a liveArc<AtomicU32>view of the setting, shared with the running signer (AppState::auto_approve_limit; aconnect_changedhandler keeps it in step), so setting it to 0 stops silent answers immediately — no stop/start, and an externalgsettings setis honoured too. The handler is installed on thegio::SettingsinstanceAppStateholds for the process: it is owned by that GObject and would die with it, and a bareSignalHandlerIdkeeps nothing alive. - Replay and freshness (H1).
kind:24133is ephemeral, so the relay layer never stores or deduplicates it: every delivery of the same event reaches the responder again — a second relay, a reconnect, or an attacker replaying a captured request.signer::ReplayGuard, checked in the responder loop beforehandle_request, drops a wrapper event whosecreated_atis more thanREQUEST_FRESHNESS(120 s) from now, one minted before this run started, and any event id already seen (bounded bySEEN_CAPACITY). The dedup is in memory only: a stop/start cycle inside the freshness window re-admits a request minted shortly before the restart (a persisted high-water mark is the documented alternative; not implemented). - Approvals go through
signer::approval::Approver: the responder asks over a channel, the dialog answers, and a timeout or a missing UI denies — never allows. Client names/URLs shown in the dialog are client-supplied and must be treated as display hints only. - The policy check and the prompt live on the responder side, next to the
request, but the registry lock is never held across an
await. - Relays come from GSettings (
relays);REGENT_RELAYS(comma separated) overrides them, which is what headless tests use. The default iswss://nostr.kosmos.orgbecause many public relays reject or rate-limitkind:24133— pairing silently times out on those. - A permission is stored only once the answer is produced (M1).
gate()returns the user's verdict but does not writeapps.json;authorize_innerre-checksidentity_for(and, for a silent answer,permits) after the lastawait— the approval dialog and the unlock prompt both give the user time to revoke or rebind the app — and only then stores "always" and fetches the key. A revocation or rebind during either prompt therefore denies, and a cancelled unlock leaves no permission behind. Serialized now (L4): the in-app andnostrconnect://-link pairing dialogs go through the sameApproverqueue (Approver::ask_pairing→ thePrompt::Pairarm inui/approval.rs::install), so a pairing prompt can never stack over a request prompt; the re-check above still makes the race fail closed. - Two traps that make a signer look "hung" against a real relay. Both are fixed;
do not reintroduce them:
- Subscriptions must target relays explicitly. With gossip enabled (the
default) a plain
Filteris routed by its authors; a#p-only filter resolves to no relay at all, so the REQ is never sent and the subscription looks registered while nothing arrives. We build manual(RelayUrl, Vec<Filter>)targets. (Symptom: works againstnak serve, hangs against a real relay.) - Wait for the relay to be connected before subscribing. A REQ sent while
a relay is still
Pendingis registered locally but never transmitted. Localhost connects instantly, so this only shows up onwss://. We useadd_relay(…).verify_subscriptions(true)(which also re-sends the REQ after a relay reconnects — essential for an always-on signer) plusconnect().and_wait(…).
- Subscriptions must target relays explicitly. With gossip enabled (the
default) a plain
- On start the app logs
regent: signer listening on N relay(s) as npub1…— the public key only, never the secret. That line is what headless checks assert on.
Notifications and the approval deadline (M9)
- A prompt is an
AdwDialoginside the window, so if the window is not focused nothing tells the user. Every responder-driven prompt therefore also raises agio::Notificationfrom theinstalldrain inui/approval.rs: pairing, sign, encrypt, decrypt and the unlock prompt. The in-app pairing dialog is reached by a click, so it does not notify. - Only when the user is away (
!gtk::Window::is_active()).REGENT_NOTIFY_ALWAYSforces "away" for the acceptance test —gtk4-broadwaydreports the window active even though no window manager can focus anything. Same kind of documented test override asREGENT_RELAYS. - One id (
"approval") so a second prompt replaces the first; the drain is serialized, so only one prompt is ever open. Withdrawn as soon as it resolves. - One-way notices use their own channel and their own id. A NIP-46
logoutremoves an application, and nothing else tells the user, so the responder sends aNoticethroughApprover's separatenoticeschannel, drained byui::approval::install_notices. A second channel keepsPromptmeaning "needs an answer" and a one-way notice out of a drain that blocks inpresent_questionuntil the dialog is answered; the notice id ("notice") keeps it from replacing, or being withdrawn with, a prompt's notification. It is raised unconditionally — theuser_is_awaygate exists for prompts, and a notice has no dialog on screen — and headless logs it to stderr instead. - The body is per category and never carries the client name, event kind or content — a notification body renders on the lock screen, and the client's name is attacker-controlled display data, exactly like the activity log's rule.
- Click to open:
set_default_action("app.focus")plus anapp.focusaction that presents the window. Verified mechanism: GLib's freedesktop backend sendsactions = ["default", ""]and adesktop-entryhint; on a body click GNOME Shell emitsActionInvoked(id, "default")and GLib activates the app action in-process (theorg.gtk.Notificationspath would callActivateAction("focus")on the app instead — the same action name either way). - The dialog's content puts the decision first. Heading, then one sentence of
our own words — never "it", because the application's name is a row and the
body must not carry client text (it is not selectable) — then the payload as a
bounded, scrollable card, so a long note cannot push the buttons off screen.
"Signing as", "Application", the event kind and its client-requested
Created at timestamp stay above the fold (kind and timestamp are part of
what is signed); the verifiable-but-secondary fields (client key, declared URL,
raw tags, method, peer, "asked for") live in a collapsed Details expander.
Anything the dialog cannot show in full is disclosed by an
AdwBannerabove the fold — truncated content (against the responder'sCONTENT_LIMIT), hidden tags/tag values, and a timestamp more than an hour from now — so nothing that is signed or encrypted is invisible (WYSIWYS, H2). A pairing whose client declared no name also gets a name field there — under "Application", above the Details — because that is the one prompt where the user decides to trust an app and can still give it a name; the entered name travels back in theAnswer. The "name and URL are supplied by the application" warning is shown on the pair screen only — on an already-approved app's request it is banner blindness. Both this dialog and "Connect an app" useplain::DIALOG_WIDTH(480) so neither resizes as the user moves between them — the approval dialog pins it withplain::alert_width, becauseAdwAlertDialogignorescontent-width(see trap 17). - The dialog owns the deadline, and it is absolute.
ASK_TIMEOUT(60 s) is turned into anInstantwhen the ask starts and travels to the UI in thePrompt; the dialog answersDenyand closes itself when that instant arrives (glib::timeout_add_local_once→try_send→AdwDialog::force_close), which is what withdraws the notification on time. The responder keeps a longer backstop (ASK_BACKSTOP, 90 s) for a missing or wedged UI. Anchor it at the ask, never at presentation: prompts queue behind each other in the drain, so a deadline re-armed when the dialog opens could outlive the backstop, and the UI's answer would land on a dropped receiver — the dead-button dialog this exists to remove. A prompt whose deadline has already passed while queued is answeredDenywith no dialog and no notification. User-initiated flows (in-app pairing, export's unlock) passNone. - The unlock retry loop shares one deadline across passphrase attempts — a wrong passphrase must not buy the request more time — and reports it in the dialog body rather than stacking a second error dialog.
- Which interface is used depends on the machine, and the gtk one is strict.
GLib picks its backend by priority:
org.gtk.Notifications(100) whenever that name is owned — every real GNOME session — elseorg.freedesktop.Notifications(0). The gtk path refuses the notification unless GNOME Shell can resolve<app id>.desktopin its app index, and its D-Bus call passes no error callback, so a refusal is completely silent: no banner, no stderr, no trace.warn_if_the_desktop_is_missing()inapplication.rsis the only place that failure can be made visible. Note that the freedesktop backend does log a warning — so "no warning in stderr" does not mean "no notification was attempted". - GIO drops a desktop file whose
Execdoes not resolve. It validatesExecwhile parsing and discards the whole file, so the app never enters the index and every notification is refused. That is whyregent-deployrewrites the installed copy'sExecto the absolute~/.local/bin/regent: a session's PATH (a systemd user session gets/usr/local/bin:/usr/bin) has no~/.local/bin, while the packagedExec=regentis correct for a/usrinstall. connect_activateis idempotent: it presents the existing window instead of building another. Activation arrives for a notification click and for launchingregentagain, and a second window would share the state and show the same dialog twice.
Windows and first run (M10)
- Two windows, one
AppState.window.rsbuilds both and holds theWindowsregistry; the identities window is chrome (data/resources/ui/keys.blp) around the existingKeysView. A secondAppStatewould mean a second registry and a second signer on one device key (see M5), so the registry is created once inapplication.rsand shared. The window is 420×560: tall enough for the first-run empty state and the add/import alert dialogs, because GTK never resizes a mapped window, so the default has to fit the tallest thing it shows. - The invariant: the main window is presentable exactly when the responder can serve prompts. The approval dialogs are parented to the main window, so a request must never arrive without it. With no keys there is nothing to sign with and nothing to listen for, so the identities window is the whole app. With a key the main window exists and the signer runs, but it may be hidden in the background (M12): the approval drain presents it for a dialog and hides it again once the request is answered. Closing the main window is no longer a plain quit — see M12 — but with no key, or a stopped signer, it still quits, because a hidden window that can answer nothing is the "signer that answers nothing" this shape exists to avoid.
- The launch decision (
Windows::build+present_primary): no keys ⇒ present the identities window only; keys ⇒ the main window, whose first page is Apps.follow_keys(astate.listencallback) follows the transition: the first key presents the main window and leaves the identities window open, and removing the last key hides the main window and presents the identities window again — first-run mode. Acting on the transition rather than on everynotify()is what keeps a profile fetch or a lock from re-presenting a window the user just closed. The choice is logged (no identity key yet, opening the identities window/identity keys found, opening the main window): it is the one part of the launch that cannot be observed from outside, and acceptance asserts on it. Windows::primary()is the single rule for "the window the app is", andapp.focus,app.lockandpresent_preferencesall go through it. Do not reintroduceapp.windows().first()— it is creation order — and note thatapp.focusused to present every window, which would pop the hidden identities window open on every notification click. With the window able to be hidden, a dialog is parented throughWindows::visible_parent()(active_window(), elseprimary()): anAdwDialoginside a hidden window is silently invisible, sopresent_preferences/present_about/present_connect/pair_urimust never parent to a window that is off screen.- The identities window is created once and
set_hide_on_close(true):AppState::listencannot unregister and its closures capture widgets, so a window destroyed and rebuilt would leave listeners pointing at dead widgets.present_identitiesmakes it transient for the main window while that is visible: GNOME Shell's focus-stealing prevention shows a " is ready" notification instead of raising an already-mapped window that has no valid activation token, and a transient is focused with its parent. With no visible main window (first run, last key removed) it stays standalone. - Preferences (
ui/preferences.rs) is anAdwPreferencesDialog— libadwaita 1.6 deprecatedAdwPreferencesWindowin favour of it — built once and re-presented (AdwDialogre-presents after being closed), with its listeners registered once, because the lock state changes while it is open. It holds the signer's run state (Start/Stop), the vault group and the auto-approval limit. The signer moved here from the "Connect an app" dialog: its run state is not what that dialog is for, and Start/Stop sat above a pairing flow it did not belong to. Deliberately not relays: the running signer holdsconfig.relaysfrom start, the bunker URI advertises them andget_relaysserves them, so a mid-run edit would mean "changed, but not until restart, and the paired clients were told otherwise". Reachable byCtrl+,everywhere but by pointer only from the main window — deliberate, since in first-run mode there is nothing to configure yet. - The primary menu (main window) carries "Manage identities…", "Preferences…" and "Quit". The identities entry is not redundant with the switcher's: the switcher hides itself while there are no keys, and the last-key-removed state is exactly when the menu is the only pointer route back.
- The vault loads synchronously —
KeyStore::connect()is plain file I/O and theasyncwas vestigial from the removed keyring — so the launch decision can depend on it andstate.store()is no longer anOption. A vault that exists but cannot be read is fatal:application::runprints and exits non-zero beforeapp.run(), because starting with an empty vault would let the next save overwrite the real keys (the shape M8 closed).
Running in the background (M12)
- Closing asks, hides, or quits.
close-action(GSettings, defaultask) picks:askshows anAdwAlertDialog(Cancel / Keep Running / Quit) with a "Remember this choice" checkbox;backgroundhides;quitends the app. The dialog's default and suggested response is Keep Running, and its close response is Cancel, so Escape and the dialog's X mean "stay as you are".Windows::request_closealways returnsPropagation::Stop— GTK must never destroy the window — and the choice is only offered whileSignerRunner::status()isRunning: with no key, or a stopped signer, closing quits as before. While a prompt is on screen the close is ignored, so the ask dialog cannot stack on top of it (only a keyboard/WM close reachesclose_requestat all; the modal prompt blocks pointer closes). - The window may be hidden while the signer runs. Hiding a window keeps the
process alive (GtkApplication holds while a window exists), so no
g_application_hold()is needed.PrimaryHandleis the main window plus oneautoflag:present/hide/toggleare user-initiated and clear it;present_for_promptpresents a hidden window and sets it; the responder'sNotice::RequestAnsweredcallsrestore_after_prompt, which hides only if the flag is set. The hide follows the request, not the dialog — a locked vault asks twice (approve, then unlock), so hiding whenpresent_questionreturns would flicker and strand the unlock dialog on a window it just hid. - Notifications still fire while hidden.
notify_pendingruns beforepresent_for_prompt, so the user is away (the window is hidden) and a notification goes out; a click lands onapp.focus→present_primary, which is a user-initiated present (it clears the auto flag, so the window stays). - The status icon (
ui/tray.rs) is a ksni StatusNotifierItem on the shared tokio runtime: Show/Hide Regent, Preferences…, Quit Regent. Left-click opens the menu (MENU_ON_ACTIVATE), notActivate: the GNOME AppIndicator extension waits out the double-click interval on every click when anActivatemethod exists, so the menu-only interface is what makes it open at once. It holds onlySendstate and talks to the main loop over anasync_channel; visibility/status/pending go back through a sharedArc<Mutex<TrayModel>>andHandle::update.show-tray-icon(default true) gates it. A missing host (stock GNOME without the AppIndicator extension) is not an error:watcher_offlinelogs (once per offline event) and returnstrue, so the icon appears the moment a host does. A start is asynchronous, sotray_startingguards against a second activation putting two items on the bus, and the completion re-checks the preference before showing it. - GNOME's Background Apps listing (and autostart) needs the
org.freedesktop.portal.Backgroundportal — hiding the window alone does not list the app.portal::request_backgroundis a hand-rolledgioD-Bus call (notashpd, which would pull a second zbus major in beside ksni's). Called when hiding to the background and at startup whenautostartis set.--backgroundstarts with no window (the autostartExec); the flag is stripped from the argv GApplication parses. g_application_quit()never emitsclose_request, so the menu's Quit, Ctrl+Q and the tray's Quit bypass the dialog with no "quitting" flag.
Apps, permissions and the activity log (M5)
apps.jsonis the single source of truth for what an app may do without asking, and it is shared:AppStateowns oneArc<Mutex<AppRegistry>>, and the responder and the Apps page read the same one. "The policy table drives behaviour" means revoking on the Apps page changes the responder immediately.- Create
AppStateonce per process (inapplication.rs, captured by the activate closure), not per window. A secondAppStatewould mean a second registry and a second signer on the same device key. - The Apps page shows one
AdwExpanderRowper app, with a per-appview-moremenu as its only suffix (Rename… and Revoke), one Remove row per stored permission (kind forsign_event, method for encryption), and Forget all. The list is newest approval first (list_forsorts byapproved_at, descending, ties in reverse insertion order), so a re-pairing moves an app back to the top and pre-approved_atentries (timestamp 0) sit at the bottom.apps.jsonstill stores them in insertion order — the sort is a view rule, not a storage one. The title is the app's display name: the user's ownlabelfirst, then what the client declared, else the shortened npub. The collapsed byline is the host the app declares (declared_host), falling back to the shortened npub when it declares none; the full public key and the full URL are rows in the details. A declared URL is display data the client controls — it proves nothing, and the host is shown so the byline stays short. - A client may declare no name at all (the bunker direction often sends no
metadata), leaving only an npub.
App.labelis the user's own name for it, deliberately separate from the client'sname:approverebuilds the entry on every pairing, so a label kept innamewould be lost the next time a metadata-less client reconnects.App::display_name()prefers the label, andAppRegistry::client()returns it, so the approval dialog and the activity log show what the user calls the app. The "wants to connect" dialog asks for a name when the client declared none, andapprovepreserves an existing label when the dialog collected none. - The activity log (
store/audit.rs) records metadata only: app, method, event kind, outcome, time.Entryhas a typedkind: Option<u16>and deliberately no free-form detail field, so event content, plaintext and ciphertext cannot reach it. Unapproved requests are not logged, so a stranger who knows the device pubkey cannot flush the history. Bothactivity.jsonlandapps.jsonare mode 0600 — including the log's trim rewrite, which would otherwise recreate it world-readable. - One bounded(1), coalescing change channel (
AppState::changes) wakes both pages after a registry or log change; the responder pings it fromrecord()and registry mutations, andtry_sendnever blocks a signature. Never send while holding the registry lock. Because it is shared, the Apps page compares a(pubkey, name, policy)snapshot and skips the rebuild when only the log changed — otherwise every answered request would collapse the expanders. apps.jsonis written atomically (temp file + rename), and a corrupt one is moved toapps.json.corruptrather than silently overwritten.logout(NIP-46 "forget the client") revokes the app and its permissions — the only meaningful "drop session" in a stateless responder.get_permissionsis a Regent extension, not NIP-46; the requestedpermsfrom aconnect(params[2]) are shown in the pairing dialog but never auto-granted.
Multiple identities (M7a)
- The invariant: the responder resolves a request only from the app's
stored identity (
App.identity). The UI's current identity (GSettingscurrent-identity) is never read at request time — it scopes the Apps and Activity pages and sets the default for new pairings. Switching it therefore never re-identifies an existing app. - Each approved app is bound to one identity at pairing. NIP-46 clients mint a client keypair per connection, so the same app can be paired under two identities in parallel (two client pubkeys → two registry entries). A client that reuses one keypair for two identities cannot be distinguished — requests carry no identity field — so re-pairing rebinds, and that resets the policy.
- Rebinding clears the stored policy.
AppRegistry::approveonly preserves a policy when the identity is unchanged; a permission granted while signing as A must not carry over to B. The approval dialog warns about this. - The registry is keyed by client pubkey only (unique per connection). Audit
entries carry
identity: Option<String>; pre-M7 entries have none and are shown under every scope (M7b). - The vault/API split:
KeyStore::list_user_keys()(metadata only, works while locked),user_key(pubkey)(only while unlocked),SignerConfig.keys: IdentityKeys(Fixed/Manyfor tests,Store(Arc<KeyStore>)in production). The responder opens the vault after the approval, just before signing. AppState::refresh_identitiesresolves the current identity (setting valid, else first key) and binds legacy apps (bind_legacy) at startup and after any key change. Pre-M8 this also migrated a keyring item; that is gone.- Identities window: list, Add/Import, per-key Re-fetch profile / Rename /
Copy / Export / Remove. (Which key is current is the header switcher's job,
not this window's.) "Re-fetch profile" (
AppState::refetch_profile) loosens all three automatic gates for that one key — the 7-day discovery TTL, the 1-day directory-fallback backoff and the 1-day NIP-05 check backoff (Profiles::mark_profile_stale), so the row updates now instead of at the next refresh. That includes a discovery query — the per-author request that tells the directory relays this machine holds the key — which is exactly why it is behind a deliberate click; a click while a fetch for that key is already running (profile_fetch_in_flight, which an automatic refresh claims too) does nothing and says so. When it lands, the menu answers with what the fetch found (store::profiles::FetchOutcome): "Profile updated", "Profile is up to date" (the relays had nothing newer — including the version already held) or "No profile found"; so the "checking" toast does not just hang (the outcome dismisses it — it is not outranked, because a high-priority toast only pushes the previous one back into the queue and it would come back stale). A moved clock, or an entryput_relay_listcreated only for its attempt clock, is not an update: "updated" means the name, picture or declared address changed — a NIP-05 verdict arrives later, fromensure_nip05's own round trip, so a flip of that on its own is not an update. It cannot make anything worse either: the cached name, picture, relay list and every watermark are untouched, a profile is stored only when it is newer thankind0_at, and an address can only be un-verified by a definitive non-match — an unreachable domain leaves the confirmed one in place. Removing a key clears it as current, revokes the apps bound to it (the dialog names them), and deletes the item. - The identity is shown as "Signing as {name}" with the npub beneath it, not
as
{name} ({npub}): in the approval dialog it is a stacked field (optionally the npub alone when the key has no name), in the Connect dialog and the Apps page it is anAdwActionRowtitle plus subtitle. In-app pairing uses the current identity and warns when it would rebind an existing app. - Headless:
--headless/--pairtake--key <npub|hex>(default: the current identity). Serving resolves per app, so headless needs no single "active" key.
The multi-identity UI (M7b)
- Header identity switcher (
ui/switcher.rs, Fractal's account-switcher pattern): aGtkMenuButtonshowing the current identity's avatar (the kind-0 picture when one is cached, else initials), opening a popover with one row per key (avatar,display_nameor key label, then one short line, a check on the current), then "Manage identities…" (opens the identities window). Hidden when there are no keys; rebuilds on key and selection changes; both the header button's label and the rows are sorted by what they show. Holds theWindowsregistry weakly: the main window owns the switcher, so a strong reference would be a cycle. - The switcher's second line is a verified NIP-05 address when the domain
confirmed it for this key (
Profile.nip05 == Profile.nip05_ok): shown as published, because that address is what the user recognises, and the popover widens for a long one. Pastplain::key's 48-character natural-width cap it is end-ellipsized rather than clipped, so the popover cannot run off the screen. Without a verified address the line is the key:plain::shorten(npub, 12, 7)— 20 characters, shorter thanplain::shorten_npub's 31 because this popover also carries the avatar and a check mark inside a 420 px window. The tooltip always carries the full npub. - That line carries
.caption: about the size a key renders at in every row subtitle (12.0 pt against a subtitle's 12.2 — the class is 82%, a subtitle'ssmalleris ~83%; the 20-character npub cut measures 145 px there against 176 px at body size), so the switcher is not the one place a key is body-sized and the bold name above it stays the loudest thing in the row. - In a switcher row the name is bold and the value is not. The rows are
GtkButtons and libadwaita bolds every button's text (button { font-weight: bold }, no.flatexemption), which is exactly what the identity's name should look like (700, measured withget_pango_context().get_font_description()). The npub/NIP-05 beneath it is a value and stays normal weight —label.key-valuesetsfont-familyandfont-weight: normalfor that (the class beats the theme's element selector). The avatar's initials are bold too, by libadwaita's ownavatarrule. - Pages are scoped to the selected identity: Apps lists only that identity's approvals (the title names it) and its "Forget all" is scoped; Activity filters to the identity and "Clear this identity's activity" keeps the rest. Pre-M7 audit rows (no identity) show under every scope.
- The "Connect an app" dialog names the identity a new pairing will use.
- Profiles (
store/profiles.rs): kind-0 is fetched best-effort and cached inprofiles.json(0600). Discovery goes through a directory set —PROFILE_RELAYS(wss://directory.yabu.me,wss://purplepag.es,wss://profiles.nostr1.com), overridable withREGENT_PROFILE_RELAYS, elseREGENT_RELAYS(so an overridden run — acceptance, the ignored tests, a headless check — makes no public requests), else the constant. The NIP-46 relays are never asked for profiles: they are members-only and carry none, and anauthorsquery tells them which identities this machine holds. The set is measured, not guessed (2026-11-29, 20-key sample; full data in the plan'srelay-survey): those three answered the most kind-10002 and kind-0, all fresh, 0.74–0.98 s to EOSE. The per-author union of every candidate tried was the same 15/20, so further relays buy availability, not coverage. - One REQ per author, never a batched author list. purplepag.es silently
under-returns a multi-author filter (measured: 8 of 20 keys batched, 15 of 20
per author; it also replays historical versions, so an event count is not an
author count).
author_targetstherefore emits one filter per relay, one author ever; innostr-sdkthat means onesubscribe/fetch_eventscall per identity (RelayPoolgenerates oneSubscriptionIdshared by every targeted relay, and reports success asHashMap<RelayUrl, ()>— completion is keyed on(relay_url, id), not on per-relay ids). The SDK's gossip path was considered and rejected (its store is in-process, it batches authors per relay, and it needs the same directory set anyway); see §10.7 of the profile plan for the tradeoffs and the growth path. Filters carry nolimit:limit(0)caps the stored events a relay sends to zero, so a fetch with one receives nothing at all (live subscriptions still work, which is why the signer uses it). - Three EOSE-capped waves, one newest-wins map per kind. 1. discovery:
kind-10002 + kind-0 from the directory set for an identity with no trustworthy
outbox; 2. outbox: kind-0 from the identity's own write/unmarked relays
(capped at
MAX_OUTBOX_RELAYS); 3. directory fallback: kind-0 from the directory for an identity whose own relays served nothing. Waves end on EOSE (fetch_events,WAVE_CAP5 s as the backstop). A relay is added and connected only when a wave is about to use it — a warm outbox opens no socket to the directory set at all — and never while it is still connecting, because a REQ sent then is registered but not transmitted (trap 2). Budget: warm ~1 s (one wave on the identity's own relays); cold ~2–3 s; when every relay stalls, a single identity that has to discover and then reach its outbox costs at most twoCONNECT_WAITs plus twoWAVE_CAPs (~20 s), and each further identity adds up to one cap per wave it joins — all on the async runtime. A whole-wave setup failure (a relay that left the pool) is retried one relay at a time, so it cannot discard the other relays' answers. Every event goes through oneconsidermerge that drops authors nobody asked for and anycreated_atmore than 5 minutes in the future (FUTURE_SLACK) — that is what keeps a relay from pinning a watermark out of reach. profiles.jsonholds the outbox and its clocks, written by three single-owner writers:put_metadata(kind-0, older refused — see below — setskind0_at/fetched_at),put_relay_list(setswrite_relaysonly from a strictly newer kind-10002 —created_at = 0means "nothing found" and only moves the clock, so a transient miss cannot wipe a working outbox — and always setsrelays_checked_at), andnote_recovery.put_metadataaccepts an equalcreated_at, and both halves of that matter. A newer version wins; an equal one is the same version re-fetched, so storing it is what lets a field added toProfileafter the entry was written be filled in —nip05arrived exactly that way, and with a strict>every later fetch of the same kind-0 was refused, so an existing installation could never show its address no matter how often it re-fetched. It is also what advancesfetched_at— for any same-or-newer answer, since "do we have this version?" and "whose content does the entry hold?" are separate questions: re-fetching the very same event is the steady state once an id is kept, and with a strict>an unchanged profile kept a stalefetched_at, soneeds_refreshstayed true and the app re-fetched it on every start. An older version is still refused, which is the whole point of the watermark. Equalcreated_ats are settled by the lower event id (NIP-01's rule for replaceable events) — in the merge map and in the cache, which keepskind0_idfor it — so two same-second versions cannot flip with relay order, and a relay serving only one of them cannot change what the cache holds from fetch to fetch. An entry written beforekind0_idexisted adopts the next equal-created_atanswer, which is also how a field added later gets filled in.put_relay_listdeliberately stays strict: its attempt clock advances on every call anyway, so nothing can be stranded there.RELAYS_TTLis 7 days on attempts, so an identity that publishes no 10002 is re-discovered weekly, not on every start;RECOVERY_BACKOFFis 1 day on the directory kind-0 fallback, which matters because a missing profile never advancesfetched_at, soneeds_refreshstays true. (Amber does none of this: it re-queries the kind-10002 on every profile fetch, applies it only if newer, and always asks indexers ∪ saved relays — no TTL, no outbox-only path.) Disclosure, honestly: the discovery wave leaves the machine weekly per identity (daily through the recovery clock when the identity's own relays cannot serve it), and an identity with no usable outbox keeps asking the directory for kind-0 at the refresh cadence. The ignorednak_the_outbox_relay_profile_winstest covers the cross-relay newest-wins rule, two identities and the warm path (dead directory, cached outbox) against two localnak serves on ports 10590/10591.display_name,pictureand a well-formednip05are kept — nothing else.pictureis bounded likeClientInfo.image(trimmed, ≤256 chars, blank ⇒ absent) and re-bounded on read, becauseprofiles.jsonis on disk; annip05is stored normalised (local@domain, lowercase) and only if it parses, because an unparseable address could never be verified and so could never be shown.- nip05 is shown only when verified (
store::nip05). A kind-0'snip05is self-declared, and the one place it would appear — the switcher's second line — is exactly where the identity is identified, so the domain must confirm it:https://<domain>/.well-known/nostr.json?name=<local>has to map that name back to this key. The rule isProfile.nip05 == Profile.nip05_ok, so re-declaring a different address (or a forged one) makes it unverified immediately and the npub comes back; a slow answer for an address that has meanwhile changed is dropped (set_nip05compares before storing); a definitive non-match keeps it unshown, while no answer at all (an unreachable domain) leaves a previously confirmed address in place — a blip is not evidence. The local part is email-ish (a–z 0–9 . _ % + -, any case) and only ever reaches a percent-encoded query parameter; the domain is the strict half (labels, no port/path/scheme), since that is what becomes the outbound request. Either way the attempt is recorded, so an unchanged address is asked again at most once a day (nip05_checked_for/nip05_checked_at). - That fetch goes through the same single hardened HTTP path as the icons —
store::icons::fetch_https(url, Content::Document),Content::Imagebeing the icon side — so https-only, public-addresses-only (resolved and pinned), ≤3 re-validated redirects, timeouts and a 1 MiB cap live in one place, and the domain (attacker-controlled text) cannot be turned into an SSRF. Disclosure, next to the picture-host note above: the identity's domain learns that this machine resolves that address, at most once a day. - Identity avatars are fetched, cached and rendered through the same
hardened
IconStoreas app icons (https/inlinedata:only, pinned public addresses, ≤3 re-validated redirects, 1 MiB, magic-byte raster gate — see M11).AppState::ensure_avatarsis the single "make avatars show" call, fromrefresh_identitiesand from the profile fetch's completion; it hydrates the cached picture and fetches the rest. Not gated byload-app-icons: that switch is about requesting a not-yet-trusted client's URL, while this is the user's own identity. The leak that follows is real and accepted: the picture host learns the request (and the machine's address), as the relays already do. - The fetch uses a fresh ephemeral client, never the device/identity key, so a relay cannot link an identity to this signer.
AppState::identity_labelis the single display rule: profiledisplay_namefirst, else the user's key label.- One key style, two cuts. Every
npub/hex/bunker://value is shown in the monospace font at the size the label already has, through our.key-valueclass (plain::keyfor labels we build,plain::key_rowfor a row whose subtitle is the key). Deliberately not libadwaita's.monospace: that one also switches to the code size and, on anAdwActionRow, takes the title with it — hence the two descendant selectors indata/style.css(one forAdwActionRow, one forAdwExpanderRow, whose header sits deeper), mirroring libadwaita's ownrow.property.monospace. Widths: the 31-charactershorten_npubcut is 213 px in a row subtitle (228 monospace) and the full 63-character npub is 513 (555) — too wide anywhere, so the cut stays. The switcher is the only other cut (19 characters, above); the activity view keeps its own 10/6 cut and stays out of this, because its subtitle mixes a name and a timestamp rather than showing a value. - Names are never invented, and a discovered profile name wins. The vault
label is only ever what the user typed (an empty label —
UNNAMED, "Identity key" — when they typed nothing): the create dialog has noIdentity 3default and the import dialog has noImported 1. Import carries aNamefield that is prefilled from the cached profile as soon as the pasted string decodes to a key (prefill_name:nsec/hex; anncryptsec's key is unknown until it is decrypted). A bare 64-hex string is ambiguous and is read as a secret, the way the vault reads it — so pasting a public hex key prefills a name for a different key, and importing one actually succeeds as that other identity (the store cannot tell them apart either). The user's own words always win over the prefill. The label is never overwritten by a profile:identity_labelprefers the profile at display time only, so a key imported before its profile was known simply gets its name when the fetch lands —refresh_identitiesfetches profiles for keys that need one right after any add/import/rename/remove. - The identities list shows the same name as everywhere else
(
identity_label) over the key alone —shorten_npub, monospace, with the full npub as the tooltip. It used to be"Profile · npub"on one line, where a long profile name ate the key's tail. A profile arriving goes throughnotify, which rebuilds the list (and re-sorts it by the new name); thechangespings — activity and registry traffic — only re-set each row's title, initials and picture in place (refresh_live_rows), because a reload there would close an open per-key menu for a reason the user cannot see. - Adding a key never switches the selection. A key refresh never clobbers a pick made while it was in flight (the live selection wins over the settings snapshot).
Headless mode and CLI pairing (M6)
regent --headlessruns the signer with no window (and no display): it is a plain tokio program, deliberately not aGtkApplication.regent --pair nostrconnect://…runs the same way, pairs first, then keeps serving. No options opens the GUI.- Headless denies anything not covered by a stored permission. There is no
window to ask, so the approval bridge's questions are answered
Denyimmediately (not after the timeout). Pre-approve with "Allow always" in the GUI, then run headless.get_public_key/ping/get_relaysstay automatic. - CLI pairing is the client-initiated (
nostrconnect://) flow: parse the URI, subscribe to the client's relays (kept inSignerConfig::extra_relays, not inconfig.relays, so they never leak into the bunker URI orget_relays), register the app, then send theconnectresponse whoseresultis the client's secret, p-tagged to the client and signed by the device key. Running--pairis the consent; permissions are never auto-granted, and the URI/secret are never printed or logged.--pair -reads the URI from stdin (I1), so it need not appear inargvor history. Thebunker://query is percent-encoded withurl::form_urlencoded(I3), so a relay URL cannot smuggle a second query parameter. Client-supplied relays arewss://only and at mostMAX_CLIENT_RELAYS(5), and a literal IP that is not globally routable is refused — aws://or169.254.x/loopback relay would otherwise turn a hostile URI into a local-network probe. TheREGENT_RELAYStest override skips both checks (as it already lets a test point the signer atws://127.0.0.1); the relays that survive are shown in the pairing dialog's Details. - The responder answers
connectwith"ack"for an already approved client even without the secret — a client-initiated pairing proves key possession by receiving our response. A new client still needs the secret. - The pairing secret rotates (L1).
SignerConfig.secret(and thebunker://config.uri) are sharedArc<Mutex<String>>s; a successful new pairing — the responder'sconnectarm afterapprove, andpair_clientaftercomplete_pairing— callsrotate_secret, which mints a fresh 96-bit secret and rebuilds the URI. So a copied/shoulder-surfedbunker://string stops pairing a new client after the next pairing; every approved client keeps reconnecting through the"ack"path above, unaffected. The secret was already per-run (random_secret()infrom_store), so this only shortens its life within a run. The presented secret is compared in constant time (subtle::ConstantTimeEq), never==. - One instance only. Two signers on one device key fight over
apps.json. The GUI owns the D-Bus nameorg.kosmos.raucao.Regent, soNameHasOwneris the friendly first message ("Regent is already running"), but it is not the guard: a headless run owns no name, and with no session bus (a server, an SSH box) neither does a GUI. Both the GUI (application::run'sstartuphandler) and headless (headless::serve) therefore take an unconditional exclusiveflockonregent.lock(mode 0600) throughinstance::claim, which fails closed if the lock file cannot be created or locked. That is what catches two headless runs, a GUI beside a headless one, and a second GUI on a machine with no session bus. The lock is taken instartup, which GLib emits only for the primary instance, so a secondary forwarding anostrconnect://link still reaches the primary; a refused instance also short-circuitsactivate/open, becausequit()alone does not stop them being emitted. The kernel drops the lock on exit, so it cannot go stale. - Errors are loud:
--headless/--pairprint a message and exit non-zero for a bad URI, an unreadable vault, no identity key, or a relay that refused the connect response. - Unlocking for an unattended run:
--passphrase-file <path>(a small regular file, mode 0400/0600 — never argv or the environment), or a systemd credential at$CREDENTIALS_DIRECTORY/regent-passphrase, which wins when present. It is opened once (read_passphrase_file, so no metadata/read TOCTOU), refused if group/other can read it (not merely warned about), read viatake(4097)into aZeroizingbuffer, and never logged. Without it a locked vault simply denies the sensitive methods.--pairneeds no identity secret and works while locked. - In-app pairing (Apps page → "Connect an app…" or the primary menu): paste the
nostrconnect://string, then the same approval dialog used for responder questions, through the same serializedApproverqueue (Approver::ask_pairing; L4). On allow, the client's relays are added to the running signer andsigner::pair_clientregisters + answers. If the signer is stopped, it is started with the client's relays first. TheSignerRunnerhas aStopped | Starting | Runningstate so a second start cannot put two responders on one device key. - Opening a
nostrconnect://link pairs straight away, over the window the app is (Windows::pair_uri), without opening the "Connect an app" dialog — so its errors must not be parented to that dialog, which is never presented on this path.ConnectDialog::report_errortherefore falls back toWindows::visible_parent(); otherwise a bad URI, or a build with no identity key (as a fresh nightly has), would fail silently. Only the stable build is the system'snostrconnect://handler (see the dev deploy section). - The other direction needs no Start button. "Show Regent's code" is gated on
a running signer — the
bunker://URI only exists while it listens — so expanding that row starts the signer if it is stopped. That is why the dialog carries no Start/Stop: the two directions are "paste a code" (auto-starts on pair) and "show a code" (auto-starts on reveal). Start/Stop lives in Preferences. - A successful pairing closes the "Connect an app" dialog and brings Apps
forward (
Windows::show_apps), and there is no "Client paired" confirmation: the new app is already in the list the user lands on. The client-initiated direction closes it inpair_now; the bunker-URI direction has no code path in the dialog at all — the client connects from outside — soConnectDialogsnapshots the current identity's app count onpresent()and closes when the registry grows past it (thechangespingrecord()sends). The other place that grows it, a rebind, moves the app into that same identity's list, so it is noticed too. Signer::add_client_relaysmirrorsstart: add withverify_subscriptions, wait until connected, then subscribe an explicit(RelayUrl, Vec<Filter>)target. Subscribing before the connection lands is trap #2 again, and it looks fine because the pairing itself publishes explicitly — only later requests silently never arrive. The client's relays join the shared, growable listening set (response_targets), but a reply is published to the relay the request arrived on plusconfig.relays— never to another application's relay, so one app's prompt timing and response sizes are not observable to a client that joined a different relay.pair_client(shared by the GUI and--pair) approves before publishing: the client validates the secret and usually sendsconnectimmediately, which a new client cannot do without the bunker secret.- Known limitation: a manual stop/start drops the client's relays
(
extra_relaysare per-run). Spec-compliant clients recover viaswitch_relays; others need re-pairing. Persisting per-app relays inapps.jsonis the clean follow-up — and would also let a reply use a client's other relays; today it is the arrival relay plus the configured ones. - Still deferred: D-Bus activation (a
.servicefile +DBusActivatable).
The key vault (M8)
- One file,
keys.json, atglib::user_data_dir()/org.kosmos.raucao.Regent/(mode 0600, written atomically to a uniquetempfile::NamedTempFileand renamed over the target, a corrupt file moved to a timestampedkeys.json.corrupt.<secs>.<nanos>so a second corruption does not erase the first). It holdsversion, an optional plaintextdevicensec, andkeys: [{pubkey, name, ncryptsec}]. Aversionabove 1 is refused in place (left on disk, not quarantined — a newer vault is intact, not corrupt), so an older Regent never silently downgrades it. There is no Secret Service and nooo7dependency: the login keyring was never at-rest protection (unlocked at login for the whole session, keyed off the login password). The data, config and cache directories — and the lock file's directory — are created 0700 through the sharedstore::create_private_dir(L6), not with the process umask. - Vault mutations are serialized (M9).
add_user_keyandchange_passphrasehold atokio::sync::Mutex(writes) across their whole body, because each encrypts and then updates state — interleaved, they could write a key under the old passphrase beside keys re-encrypted under the new one, producing a vault no passphrase opens.save()additionally holds astd::sync::Mutex(save_lock, never across anawait) across read-clone → write → rename, and the temp file is unique, so concurrent saves cannot collide on a sharedkeys.json.tmp. (profiles.jsonuses the same unique-temp write.) - Identity keys are NIP-49
ncryptsec(log_n = 16, rust-nostr'sMAX_LOG_N = 18caps a tampered entry), all under one global passphrase. Thepubkeyis stored beside the ciphertext solist_user_keysand the signer'sget_public_keywork while locked. - The device key is deliberately plaintext in the same file. It is rotatable and low value (a leak exposes future request plaintexts and allows response spoofing to paired clients, but forges no identity signature), and it must stay available so a locked Regent still receives requests, records them and can ask to unlock. It is the only exception to the "never in the clear" rule.
- Cache the keys, never the passphrase. Unlocking decrypts every entry into
HashMap<PublicKey, Keys>; the passphrase is used and dropped (Zeroizing). Add/import/change ask for it again. Caching the passphrase instead would be strictly worse: withkeys.jsonreadable on disk a memory dump holding it decrypts everything, it is the reusable secret (exports, other clients, other machines, backups), it enables offline scrypt attack on every backed-up copy, and it pays a synchronous scrypt (~70 ms and 64 MiB atlog_n16) on every request — a 100-event burst would be ~7 s of one core. add_user_keyverifies the passphrase against an existing entry before writing, so a typo cannot quietly create a second passphrase that opens only the new key.change_passphraseneeds only the new one (we hold the keys) and re-encrypts every entry.rename/forgetneed no passphrase at all. The unlocked vault is the authorisation (L3): bothchange_passphraseandexport_user_key_encryptedrefuse a locked vault and require no re-entry of the current passphrase while it is open. That is deliberate — the control is the unlock plus the auto-lock timeout, not a second prompt — and is an accepted tradeoff recorded from the review, not an oversight.- Auto-lock is a hard timeout since the unlock (
lock-timeout, default 900 s, 0 = never), checked by a 30 sglibtimer instate.rs, plus "Lock now". It is deliberately not an idle timer that request traffic resets — a chatty client would hold the vault open forever. The elapsed time is measured withCLOCK_BOOTTIME(store::keys::boottime), notInstant, becauseCLOCK_MONOTONICstops while the machine is suspended — a laptop that slept through the timeout must still lock on resume.boottimeis the oneunsafecall in the tree (alibc::clock_gettime). The vault also locks immediately on suspend (org.freedesktop.login1PrepareForSleepon the system bus) and on the screen locking (org.gnome.ScreenSaver.ActiveChangedon the session bus) — both best-effort, since a machine without logind or a screen saver just keeps the timer. Headless never auto-locks (there is nobody to re-prompt). Dropping the cache triggers rust-nostr'snon_secure_erase, a best-effort volatile overwrite with no contract; the docs must not pretend it is a guarantee. - The vault gate follows the policy gate, and changes nothing about it:
sign_event/nip04|44_encrypt|decryptare decided first (a stored permission, or a dialog), and only then — if the vault is locked — doesPrompt::Unlockgo over the same approval channel. That order matters: a client that is unapproved or explicitly declined never burns a passphrase prompt. A second concurrent request sees "already unlocked"; a timeout, a missing UI or a refusal denies.connect,get_public_key,get_relays,ping,get_permissions,logoutandswitch_relaysnever touch the vault and keep working while locked. - Audit fidelity:
authorize()opens the vault beforerecord(), so a request the vault refused is logged aslockedand never assilent/allowed— the log must not claim an answer that was never produced. Never reintroduce akeys.get()that runs after the record. - UI: a header lock/unlock button (
app.lock,<primary>l) whose icon and tooltip show the state — a closed padlock and "Locked", an open one and "Unlocked" — not what clicking does; the button itself still toggles. Preferences owns the passphrase ("Change…"), the auto-lockComboRowand a lock row that toggles with the vault's state: unlocked it offers "Lock", locked it offers "Unlock…" through the samepresent_unlockdialog the header button uses — which is what lets a locked user reach "Change…" without leaving Preferences. It is inert until a key (and so a passphrase) exists. The identities window's add/import dialogs carry the passphrase field (with a confirmation only when that call sets the passphrase). Export needs the vault open first (with_unlocked). - Export and import hygiene (L2). The export password is always confirmed
and at least 8 characters (
PassphraseFields::export; the purevalidate_passphraseis unit-tested), so an accidental empty submit cannot encrypt a key under"". The import key field is anAdwPasswordEntryRow(masked), so a pastednsecis not shown in cleartext.plain::copy_secretcopies an exportedncryptsecor abunker://string and clears the clipboard again after 60 s if it still holds that value. - Never log, print or put the passphrase in argv/env. The passphrase is
Zeroizingwhere it crosses the vault and the headless path, and is dropped as soon as the unlock lands. The GTK dialogs now clear their entry rows on every response and wrap the extracted passphrase / pastednsecinZeroizingbefore the async call (L5) — still hygiene, not a blanket guarantee. Verified: on drop,nostr::SecretKeycalls secp256k1'snon_secure_erase(), a volatile overwrite — not a guarantee (copies can survive in registers or on the stack, and there is noZeroizeOnDropcontract). Treat in-memory exposure as a real risk. - Everything async goes through
runtime::spawn, which runs the future on tokio and applies the result on the main loop. GTK objects are notSend, so a closure passed toMainContext::invokecannot capture widgets — that is why results come back over a channel instead.
UI lives in data/resources/ui/*.blp (Blueprint) and is compiled to .ui by
blueprint-compiler, bundled into the GResource, and loaded with
gtk::Builder + builder.object::<T>("id").
App icons from NIP-46 metadata (M11)
- Applications declare an
image(icon) in their NIP-46 metadata; it was already parsed and persisted (parse_client_uri,client_info,App.image). M11 is the fetch → cache → decode → render, and it is mostly a security feature: the URL is attacker-controlled. fetch_https(url, Content)is the only HTTP fetch in the app — the icon path (Content::Image, plus the raster magic-byte gate) and NIP-05 verification (Content::Document, JSON parsed by the caller) both go through it, so there is one place to audit for SSRF.fetchis the icon entry point and keeps the inlinedata:support.store::icons(IconStore) owns the disk cache and the decoded textures. Files underglib::user_cache_dir()/…/icons/, keyed by the client pubkey (validated 64-hex at the store boundary —apps.jsonis on disk and must never reach a path join):<hex>.img(the bytes that decoded, 0600) and<hex>.url(the URL last attempted, success or failure, 0600). Onereqwestclient per fetch (resolve_to_addrsis baked in at build time, so a shared/OnceLockclient could not carry the pin).- The
.urlsidecar is the retry rule.needs_fetchis true only when the sidecar URL is missing or ≠ the app'simage. A failed fetch writes the URL to the sidecar (and drops any stale.img), so a bad URL is retried only when the application changes it — never on the nextchangesping. Do not reintroduce "no icon file ⇒ fetch":changesfires on every answered request, so that is an unbounded background loop and a multiplied presence leak. - Hardening (all of it mandatory).
httpsonly (plus inlinedata:image/*;base64, which never leaves the process, bounded by a length check before base64 decoding so a hostile payload cannot allocate past the cap — L7); resolve withtokio::net::lookup_hostand refuse any non-public address — IPv4 rejects loopback, private, link-local, CGNAT100.64/10,0.0.0.0/8,192.0.0/24,198.18/15, reserved and multicast; IPv6 is allow-listed to global unicast2000::/3minus2001::/23,2001:db8::/32,2002::/16and3fff::/20(which also refuses IPv4-compatible::/96, IPv4-translated, NAT6464:ff9b::/96, ULAfc00::/7, link-local and discard ranges; IPv4-mapped::ffff:0:0/96is judged as its embedded v4) — fail closed on a mixed answer; pin the validated addresses; follow ≤3 redirects manually, re-validating and re-pinning eachLocation(a scheme downgrade or a private address dies at the hop);timeout(5s),connect_timeout(3s), no cookies/auth/proxy —.no_proxy()is mandatory: without it anHTTPS_PROXY/ALL_PROXYwould override the pinned addresses and could reach internal hosts, at the cost that a host behind a mandatory corporate proxy cannot serve icons or NIP-05 (fail-soft: initials / unverified address). URLs with embedded userinfo are refused on every hop (aLocation:can carry it). Stream the body with a 1 MiB cap. The format gate is magic bytes, notContent-Type: png/jpeg/gif/webp only, SVG and every other vector rejected before decode (a sub-KiB SVG can allocate GBs, so the byte cap alone is not enough); a ≤4096² check after decode is only a backstop. - Decode on the main loop. The fetch runs via
runtime::spawn; the bytes come back asVec<u8>andgdk::Texture::from_bytesruns in thethen(GTK is notSend). A cached.imgmay be decoded synchronously on the first paint (AppState::hydrate_icon), bounded by the byte cap;IconStorememoises the sidecar URL and the one-shot hydration so the per-ping path does no disk I/O. - Image dimensions are read before decoding.
sniff_dimensionsparses the container header (PNG IHDR / GIF screen / JPEG SOF / WebP VP8/VP8L/VP8X) and anything overMAX_ICON_DIMENSION(1024², since icons render at 32 px) is refused beforegdk::Texture::from_bytes— a sub-1 MiB PNG can describe a 30,000² canvas, and the decode would allocate the full RGBA before any post-decode check could run. A header that cannot be parsed is refused (fail closed). - No fetch before consent — now a preference, not a rule. For an
already-approved app the dialog shows the cached icon. For a first pairing it
shows the client's declared icon too, but only when
load-app-iconsis on, fetched throughAppState::preview_icon, which is memory only: no disk cache is written for an unapproved app and the texture is not put inIconStore.textures(it is handed only to the dialog'sapplyclosure), so a denial leaves nothing behind and repeated pairing prompts cannot leak textures. With the preference off there is no request and the dialog shows the generic avatar and the shortened npub. (M9's no-client-text notification bodies remain strict.) - A metadata-less client is labelled by its key. When an app declares no usable
name, the approval dialog and the Apps row showplain::shorten_npuband build theAdwAvatarwithshow_initials(false)(libadwaita's generic glyph) — never the strings"(unnamed)"/"Unnamed application"as initials, which rendered as"("/"U". Emptyname/url/image(andperms) are treated as absent inparse_client_uriandclient_info: some clients always emitname=&url=&image=&perms=, andurl: Some("")otherwise produced an empty byline instead of the npub fallback. Note the bunker direction often carries no metadata at all — noStrudel'sfromBunkerURIsends none — so this is normal, not a parse failure. - Render. A 32 px
adw::Avatarprefix on the AppsAdwExpanderRow, and beside the plain-text "Application" field in the approval dialog. The icon is decoration, never the sole identifier, and the name stays plain text — a client must not be able to forge something that looks like Regent's own UI. gcruns only on an actual Apps-page rebuild (revoke/forget/last-key-removed), never per ping, and its live set isAppState::icon_live_keys()— every client pubkey across identities plus every identity key in the vault. The page list is identity-scoped, so a live set taken from it would evict other identities' icons; and identity avatars live in this same namespace, so a clients-only live set would evict them on any Apps rebuild. Removing an identity key forgets its avatar immediately (keys_view), not at the next gc.- Identity avatars share this store. An identity's kind-0
pictureis fetched, cached and rendered exactly like an app icon (ensure_avatars,hydrate_avatar/load_avatar/show_avatarinstate.rs), which is why the two are keyed by the same 64-hex namespace. The only differences: it is not gated byload-app-icons, it is fetched at startup and on every profile refresh rather than at consent time, andshow_avatarhands the texture to an approval dialog that outlives no single rebuild. - Preference
load-app-icons(GSettings, default on) gates client icon fetching; turning it off callsIconStore::forget_textures(textures and the one-shot hydration claims, so the disk cache can be read again) and rebuilds to initials. Identity avatars are re-hydrated right after, because they do not belong to that switch. client_infoboundsimageto 256 chars likeparse_client_uridoes — it reachesapps.jsonand is now a fetch input.
Conventions
- App ID everywhere:
org.kosmos.raucao.Regent; GResource prefix/org/kosmos/raucao/Regent(fixed indata/resources/resources.gresource.xmland the same in both profiles — a GResource is per process); GSettings path/org/kosmos/raucao/Regent/. A development/nightly build is a separate identity with a.Develsuffix, selected by the Mesondevelopmentprofile (-Dprofile=development): the app id, icon, desktop file, AppStream id, GSettings schema id/path, GResource bundle name, well-known D-Bus name and XDG data/config/cache dirs all follow, and the binary isregent-develso it installs beside the stableregent.src/main.rsswitchesAPP_IDon the cargodevelfeature (a feature, not an env var, so the shared cargo target dir cannot return a binary built for the other profile); the metadata files are.intemplates configured fromapp_idindata/meson.build. The dev deploy picks it withREGENT_PROFILE=development. - Cargo is driven by Meson (
custom_target). Every source file must be listed as an input inmeson.build, otherwise edits don't trigger a rebuild. Cargo.lockis committed; builds use--locked.- All GTK calls happen on the main context. Anything arriving from a tokio task
(relay, signer) must be marshalled with
glib::MainContext::invoke. - Approval prompts must time out to Deny, never to allow. The same holds for the unlock prompt: a timeout, a missing UI or a refusal leaves the vault locked. The dialog is what enforces the 60 s deadline (see M9) — the responder's backstop must stay longer than it.
- The vault gate runs before
record()inauthorize(). Anything that reads an identity key must open the vault first, so the activity log never claims asilentorallowedanswer for a request that was refused. - Event content and client-supplied metadata are attacker-controlled text. Show
them only as plain labels (
use_markup(false)), never as Pango markup — a client must not be able to forge formatting that looks like Regent's own UI. Before it is shown or stored, client text is also stripped of control characters and Unicode bidi/directional markers (U+061C,U+200E,U+200F,U+202A..=U+202E,U+2066..=U+2069) and bounded, bycrate::sanitize(clean/clean_bound/clean_opt). That covers theconnectmetadata (client_info), thenostrconnect://fields andrequested_perms, a user label (apps::bound_label), the load paths ofapps.json,profiles.json(display_name) and the activity log (audit::bound+recent), and headless stdout (defence in depth at the print site): an ANSI escape in a name is a terminal escape in--pairoutput, and a bidi override makes an app name read as another. An empty-after-cleaning value counts as absent. They are deliberately notselectable: a selectableGtkLabelselects its whole text the moment it takes focus, and a dialog focuses its first focusable widget on open, so the first value would open with a selection highlight behind it (grey, once focus has moved on). The approval dialog deliberately has no default response, so Enter cannot approve; Escape (and the timeout) deny. The passphrase dialogs are the one exception: they carry a default response because the user is typing the secret themselves, and an empty submit simply fails and asks again. - Set
wrap_mode(gtk::pango::WrapMode::WordChar)on labels that show client text. The defaultWordmode will not break a long token (annpub, a URL), so the label's minimum width becomes the whole token and the dialog grows wider than the window. Since libadwaita ≥1.5 dialogs are an overlay inside the window (not a separate OS window), that shows up as a clipped dialog.
Verified API traps (do not rediscover these)
-
The crate is
gtk4but must be aliased:gtk = { package = "gtk4", … }. -
EventBuilderhas no finalize method innostr0.45; buildUnsignedEvent::new(pk, ts, kind, tags, content)and callsigner.sign_event(unsigned). -
rust-nostr's typed
NostrConnectMessage/NostrConnectRequestcannot parse a spec-shaped unsignedsign_event(it wants a full event withpubkey/id/sig). Hand-parse the{id, method, params}envelope. -
Clients send
switch_relaysbeforeconnect, sometimes withparams: null(not[]). Handle it, and tolerate null params. -
NostrConnectUri::parse()handlesbunker://(is_bunker(),relays(),secret()) — use it for the signer-initiated direction. Fornostrconnect://it expects a non-standardmetadata=<json>query parameter, so a spec-shaped URI (relay/secret/name/url/image/perms) fails to parse: hand-parse the client direction (seesigner::parse_client_uri). -
Requests arrive NIP‑44 encrypted; fall back to NIP‑04 for legacy clients. Respond NIP‑44.
-
Several Adwaita widgets render text as Pango markup by default:
AdwAlertDialogheading/body (heading-use-markup/body-use-markup) andAdwActionRowtitle/subtitle (AdwPreferencesRow:use-markup).gtk::Labeldoes not (it defaults to plain). Feeding markup-rendered widgets dynamic text breaks rendering on the first&(abunker://…&secret=…connection string shows nothing) and lets a client inject formatting. Build them throughcrate::ui::plain(plain::row,plain::expander,plain::dialog), which turns markup off; put untrusted text in anextra-childof plain labels. Order matters: a builder that setstitle/subtitlebeforeuse_markup(false)parses them as markup while it is still on, so an&warns even thoughuse_markup(false)follows — set markup off first, then the text (plaindoes this). Symptom: a row renders empty and GTK logs "Failed to set text … from markup". -
GApplication::send_notificationhas two backends, chosen by priority:org.gtk.Notifications(100 — used whenever the name is owned, i.e. on any real GNOME session) andorg.freedesktop.Notifications(0 — the fallback). The gtk payload isAddNotification(app_id, id, a{sv})carryingtitle,body,icon,priority(low/normal/high/urgent) anddefault-action; the freedesktop one is the classicNotify(...)withactions = ["default", ""]anddesktop-entry/urgencyhints. Only the gtk path requires GNOME Shell to resolve<app id>.desktop, and it discards every error (the freedesktop backend logs a warning instead) — so on a real desktop a bad desktop file means notifications silently never appear.withdraw_notificationbecomesRemoveNotification/CloseNotification. -
gtk4-broadwaydhas no window manager, soGtkWindow::is_active()istruefor a window nothing ever focused. Any "is the user looking at this" branch is therefore untestable under Broadway without a forced override — andGdkToplevel::state()is empty there too. -
GIO validates
Execwhile parsing a desktop file and drops the file when the program cannot be found (g_find_program_for_pathreturns NULL →goto error). The app then never appears inGio.AppInfo::all(), GNOME Shell cannot resolve it, and every notification from it is refused — silently. A desktop file for anything installed outsidePATHneeds an absoluteExec. -
A
matchscrutinee is a temporary scope that lasts to the end of the match, somatch self.cell.borrow().clone() { … None => *self.cell.borrow_mut() = … }panics with "RefCell already borrowed" — theRefis still held. Bind the clone to a local first (let existing = self.cell.borrow().clone();) and match on that. Anifcondition is its own temporary scope, so theif self.cell.borrow().is_none() { *self.cell.borrow_mut() = … }form inWindows::buildis fine. This bitpresent_preferenceson the first click; the acceptance test now activatesapp.preferencestwice over D-Bus for it. -
GtkHeaderBar'spack_startappends to the start box (left to right in call order), butpack_endprepends to the end box — so the firstpack_endends up rightmost. The main window puts every control on the left withpack_start, laid out[menu][identity switcher][lock] …in call order. Remember the prepend if a control is ever moved back topack_end. -
Never use
PANGO_ELLIPSIZE_MIDDLEfor a long, space-less token (an npub, abunker://URI). Pango pads an ellipsized line to fill its target width by widening the ellipsis glyph (pango/ellipsize.cfixup_ellipsis_run, commitc754c4d6/ pango#24, "so ellipsized text doesn't vibrate"). WithENDthat space lands at the line's right edge (invisible); withMIDDLEit lands between the…and the tail — a gap of up to one glyph (measured 12 px on a rendered npub). Do the cut ourselves instead:plain::shorten_npub/plain::shorten_urireturn a fixedhead…tailstring, and the row'sset_subtitle_lines(1)stays as an end-ellipsis backstop (whose padding is invisible). The cut lengths are sized to fit the narrowest real row — measured under Broadway with the real fonts — so the tail survives; re-measure if the fonts or row widths change. Every npub byline/row uses it (identities, Apps details, "Signing as" in the Connect and approval dialogs, the approval dialog's client key and peer), plus the Connect dialog's connection string. Note a wrapped npub also made the "Connect an app" dialog clip its bottom: the scroller measures natural height at the unwrapped width (trap 15), so a long token must stay on one line. -
A shortened subtitle hides the full value, so carry it as a plain
tooltip_text(nevertooltip_markup— it is still attacker-supplied text for a client key). The approval dialog's "Signing as" shows only the key's name, with the full npub as its tooltip (a signing key always has a name). The identities window still offers "Copy public key".AdwExpanderRowis not anAdwActionRow, but that no longer matters: its byline is shortened like any other subtitle instead of reaching into the label to change its ellipsis mode. -
A
GtkScrolledWindow's natural height is 0 unlesspropagate_natural_heightis set, andAdwDialogsizes itself to its child's natural height. So a dialog whose child is a scroller collapses to just its header bar the moment an explicitcontent_heightis removed — measured at 104px against 303px for the same content.max_content_heightonly applies when propagation is on. The "Connect an app" dialog needs both: propagation to get a real height, and the cap so the expanded QR cannot make it enormous. -
AdwDialogis not resizable: its size is decided at presentation, so a dialog whose content grows afterwards (an expander revealing a QR code) keeps its old height and hides the new content below the fold. Setfollows-content-sizeto make it track the content — "if the content resizes, the dialog will immediately resize as well". But that property ignorescontent-width/content-heightand uses the content's natural size, so a dialog that needs a fixed width must pin it on the child instead (toolbar.set_size_request(width, -1)). Measured for "Connect an app": without follows, 480×176 collapsed and expanded; with follows and no width pin, 229×176/229×492; with follows plus the pin, 480×176/480×492. Pinning the width on the scroller or the content box instead of the toolbar view leaves the height stuck. -
AdwAlertDialogignorescontent-width. It uses internal breakpoints, and a breakpoint-usingAdwDialoghas no minimum size — itscontent-widthproperty does not drive the floating size (measured: a560request still renders 300 px wide; the same value set afterpresent()is ignored too). A plainAdwDialogdoes honour it, which is why "Connect an app" worked. Setwidth-requestinstead (plain::alert_width), which the dialog honours exactly. Do not "simplify" it back tocontent_width.
Blueprint / Meson traps
- In Blueprint, property assignments end with
;, child objects do not. A widget inside a slot (e.g.[top] Adw.HeaderBar header_bar {}) must not have a trailing semicolon, or you geterror: Unexpected tokens. - Meson forbids a path segment in a
custom_target'soutput, andbatch-compile OUTPUT SOURCEDIR FILES…preserves paths relative toSOURCEDIR— so the temptingoutput: 'ui/window.ui'fails outright ("Output … must not contain a path segment"), and theoutput: '.'workaround makes the directory a target output, which then looks stale on every build and makes ninja fail to clean it (remove(…): Directory not empty) whenever the set of files changes. Compile one file per target instead (blueprint-compiler compile --output @OUTPUT@ @INPUT@), so each.uiis a real file output; the resource paths are then the plain file names (/org/kosmos/raucao/Regent/window.ui). - The app aborts at startup with
Settings schema … is not installedunless dev runs setGSETTINGS_SCHEMA_DIR=_build/data(see the run recipes inREADME.md).
Dev deploy
The build host (nuc) compiles; the workstation (nanoo, the laptop) is where
the UI is tested. build-aux/deploy-dev.sh runs on the build host,
build-aux/regent-deploy.sh on the workstation — installed there as
~/.local/bin/regent-deploy (see README.md for the one-time setup).
- Move builds by pulling from the workstation (
ssh build-host … | tar -x). Nothing listens for inbound connections on either machine; do not add an sshd to the workstation just for this. - Test installs go to
~/.local(XDG user layout) and need no root. Never install system-wide on the workstation just to try something. - Stable vs nightly:
REGENT_PROFILE=development regent-deployinstalls the.Develidentity —regent-develin~/.local/bin, its own desktop file, data dirs and D-Bus name — so it runs beside a stable/usrinstall instead of replacing it. The default profile is stable. - Only the stable build registers
x-scheme-handler/nostrconnect. The nightly desktop file deliberately omitsMimeType— system integrations belong to the installed release — though the nightly still accepts anostrconnect://argument (HANDLES_OPEN). Two desktop files claiming one scheme makes which app opens a link nondeterministic, so the dev deploy also repairs the association: GIO keeps honouring amimeapps.listdefault even after the desktop file stops claiming the scheme, sorepair_scheme_handlerdrops a stale nightly entry and GIO falls back to the stable build. - The two machines must agree on GTK/libadwaita versions; the wrapper compares them and warns. If they drift, update both before debugging anything else.
--pkgbuildsbuild-aux/regent-dev/PKGBUILD, which packages the working tree and is a preview of the real release packaging. (The AUR recipes arebuild-aux/aur/{regent,regent-git}; see "Releases".)- The wrapper updates itself: it fetches
build-aux/regent-deploy.shfrom the build host and re-execs when it differs (keeping the previous copy as.bak;REGENT_DEPLOY_NO_UPDATE=1skips it). Without that it silently kept running whatever was installed the first time — a fix reached the repo and never reached the workstation that way, with no symptom except a step that never ran. Everything else it runs is fetched per invocation; only the wrapper was a copy. - The install tree is
/usr-rooted, so its desktop file saysExec=regent(orExec=regent-develin a nightly build).regent-deployrewrites the copy it installs to the absolute~/.local/bin/regent(or…/regent-devel), because GIO drops a desktop file whoseExecdoes not resolve on the session's PATH — and GNOME Shell then refuses every notification from the app, silently (see the notification section). It checks the result and warns if the shell still cannot resolve the app. The packaged file is left alone:/usr/binis on PATH.
Releases
- Three stages, split across two machines:
build-aux/release.sh prepare|sign|publish <version>. The build host runsprepare(bump, build,meson dist, and an SSH-signed release commit); the laptop runssign(GPG: the tag and a detached tarball signature) andpublish(Gitea viagt release create, the AUR, Nostr viangit release publish). - The commit is SSH-signed, the release is GPG-signed — that is the point of
the split: the GPG key stays on the laptop and the build host never needs it.
The two formats are set per git command (
-c gpg.format=ssh|openpgp), so neither depends on the machine's global config.prepareproves it can SSH-sign before it writes anything. - The release commit is cut before
meson dist(the tarball is built from it and the GPG-signed tag points at it);signrefuses unlessHEADis the commitpreparerecorded indist/release.env, so the tag can never point at a different tree than the tarball. - Only
dist/travels between the machines. The laptop pulls it from the build host over SSH (REGENT_BUILD_HOST), so nothing has to be sent back. - The version exists in three dialects, derived in exactly one place
(
release.sh), because AppStream and pacman sort a-/.-separated pre-release above the final release:1.0.0-beta.1(tag/Cargo/meson/tarball/changelog),1.0.0~beta.1(metainfo),1.0.0beta1(AURpkgver). Do not "simplify" one of them —appstreamcli vercmpandvercmpboth disagree with the semver spelling. - Release notes live only in
CHANGELOG.md. The metainfo<releases>block is generated from it bybuild-aux/gen-metainfo-releases.py(between thereleases:begin/releases:endmarkers); never hand-edit the block. - The AUR recipes are
build-aux/aur/{regent,regent-git}— the stable tarball package and the VCS one.publishfillspkgver/_tag, the real sha256, and the signing fingerprint (validpgpkeys, with the.ascinsource), then pushes toaur.archlinux.org; the in-repo copy is updated in a post-release commit, because the sha cannot exist before the tarball does.build-aux/regent-dev/is the working-tree package the dev deploy's--pkgbuilds, not an AUR one. - Nostr is a mirror.
.ngit/release.yamlpublishes the same tarball to Blossom (blossom.kosmos.org) under NIP-82, signed by the fixed release identity (one npub, forever). Gitea stays canonical, and a Nostr failure is not fatal to the rest of the release.
Testing
- CI (
.gitea/workflows/ci.yaml, Gitea Actions) runscargo test --locked,cargo clippy --all-targets --locked -- -D warningsandcargo deny check(deny.toml). The job runs on theregent-cirunner, whose label maps to the image built frombuild-aux/ci/Dockerfile(build-aux/ci/build-image.shbuilds and pushes it to the Gitea registry), so the workflow installs nothing. The image is Arch-based because Regent'sv4_24/v1_10crate features want GTK ≥ 4.23 / libadwaita ≥ 1.10 — newer than the latest stable GNOME release (GNOME 50 ships GTK 4.22), so the oldubuntu-latestjob and the GNOME OS SDK both fail the build. The toolchain is pinned in the image (1.99.1) because the-D warningsgate is calibrated to a compiler, andcargo-denyfetches the advisory database at run time. Clippy is clean at the pinned version — keep it that way. - Against a real relay — the path that actually matters, and the only one that
exposes the two subscription traps above:
The
CARGO_TARGET_DIR=_build/cargo-target REGENT_TEST_RELAY=wss://nostr.kosmos.org \ cargo test --release -- --ignored --nocapture naknak_*tests cover the M4 approval paths end to end: the prompt carries the kind and content, a denial reaches the client, and "allow always" short-circuits the next identical request. Each test spins up its ownnak serveon its own port — sharing one port makes the parallel run hang. - The policy logic itself is also covered by fast, relay-free tests that drive
handle_requestwith a client key they control (denial, allow-always per kind, encryption remembered vs. decryption always asking, the rate limit, a dropped question denying, revoking a permission bringing the prompt back,logoutforgetting the app,get_permissions, and registry changes being announced). The audit has its own tests: a content canary never reaches the log, unapproved requests are not logged, names are bounded, andrecordtrims an oversized file while keeping it 0600. All run on a plaincargo test. - The manual re-fetch's outcomes are pinned by the ignored
nak_the_outbox_relay_profile_wins:Updatedfor a newer profile from the directory and from the identity's own relays,UpToDatewhen the relays answer with what is already held, andNotFoundfor a key nobody publishes. The three toast texts are a unit test inui::keys_view. - The NIP-05 logic is pure and covered offline: parse (every rejecting shape,
including empty labels, ports, paths and schemes), the
.well-knownURL (percent-encoding), the document match (case-insensitive both ways, malformed and hostile JSON), the display rule (nip05_ok == nip05, cleared when the declared address changes, stale answers dropped), and that an unparseable address never reaches the network. Its network half is the ignorednip05_of_a_real_domain_is_verified: setREGENT_TEST_NIP05=user@domainandREGENT_TEST_NIP05_KEY=<hex>(written againstraucao@kosmos.organd the key the About dialog links to) and runcargo test -- --ignored; it also asserts that somebody else's key does not verify for the same address. - The vault has its own fast tests (no Secret Service needed any more):
add/list/unlock/lock, a wrong passphrase refused both for unlocking and for
adding a key, rename/remove without a passphrase,
keys.jsonis 0600 and holds ciphertext for identity keys, a corrupt file is quarantined, re-import replaces, and export round-trips. Two responder tests cover the gate end to end: a locked vault that the user opens signs, and one the user does not open denies withlockedin the log (neverallowed-silently) — plus a responder test that a silent UI never unlocks. store::profiles::tests::nak_the_outbox_relay_profile_wins(ignored, needsnakand ports 10590/10591) is the profile fetch's end-to-end check: an older kind-0 on the directory relay, a newer one on the identity's own relay named by its kind-10002, two identities (so the per-author shape is exercised), and two warm-path fetches — one where the directory is alive and holds a newer profile (which must NOT be used: the cached outbox wins), and one with the directory killed (the outbox still serves).a_request_on_an_added_relay_is_answered_there(ignored, needsnak) starts the signer on one relay, adds a second, and drives a request/response through the added one — the check that a dynamically added client relay carries both directions. It uses a local second relay even whenREGENT_TEST_RELAYis set.- End to end (vault → responder → app), in a throwaway HOME:
Seeds a NIP-49
dbus-run-session -- build-aux/acceptance.shkeys.json(and checks it holds no plaintext identity key and is mode 0600), runs anakloopback against the responder, checks that a seeded identity key makes the app start the signer and that the app created its own device key in the vault, that headless--pair(with--passphrase-file) completes a client-initiated pairing (anak req --streamsubscriber must be listening, ornak servemutes the response), and that a waiting prompt raises a notification. Needsnak,gtk4-broadwayd,python3withdbus-python(forbuild-aux/notify-stub.py), and a D-Bus session for the GUI part. - The notification checks stand a stub (
build-aux/notify-stub.py) in for the desktop. It owns both notification names, so GLib takes thegtkpath a real GNOME session uses — owning only the freedesktop name would exercise the fallback and miss exactly the behaviour that broke on a real desktop. It logs every call to$NOTIFY_LOGand simulates a click the way each backend expects:ActivateAction("focus")on the app for the gtk path (what GNOME Shell does), anActionInvokedsignal for freedesktop. Gotchas there:dbus.service.BusNameand the service objects must be kept referenced (dbus-python releases a name and unregisters an object when it is collected), one object cannot be exported at two paths (add_to_connectionraises, so each interface needs its own class), andstr()on adbus.Byteis the raw character. The request itself is hand-built — an approved client is seeded inapps.jsonandnak encrypt+nak eventpublish thekind:24133request, because the app's pairing secret is deliberately unobservable. - Two more checks cover the desktop file GNOME has to find: the shipped file is
installed the way
regent-deployinstalls it andGio.AppInfomust index it, and a copy with an unresolvableExecmust be dropped — the failure that made notifications vanish on a real desktop. The app is also asserted not to print its "GNOME cannot resolve …" warning. - Loopback with no public relays and no display:
nak serve --port 10547= writable in-memory relay.nak --sec 'bunker://…' …= independent NIP-46 client.
- Headless GUI: see the recipe in
README.md(gtk4-broadwayd+dbus-run-session). - Do not test against the host's
strfry— it is a read-only mirror by design and rejects client writes. - Spikes that established the above:
/tmp/opencode/spike{1,2,5}/(throwaway).
Validation commands
appstreamcli validate --no-net _build/data/org.kosmos.raucao.Regent.metainfo.xml
desktop-file-validate _build/data/org.kosmos.raucao.Regent.desktop
glib-compile-schemas --strict --dry-run _build/data/
These are the generated files (the sources are .in templates configured from
app_id at meson setup); for a nightly build substitute the .Devel names.
--no-net is deliberate: the project URLs point at a private Gitea repo, so
the URL-reachability check fails for everyone except logged-in maintainers.
desktop-file-validate prints one hint about the Security category that we
accept.
Dev runs need the schema and resource from the build tree, otherwise the app
aborts with Settings schema 'org.kosmos.raucao.Regent' is not installed:
GSETTINGS_SCHEMA_DIR=_build/data REGENT_GRESOURCE=… ./_build/regent