docs: split AGENTS.md into per-directory notes
CI / test (push) Successful in 1m16s

The root file was loaded in every session, but most of its ~1,500 lines
are subsystem detail that only matters while working on that subsystem.
OpenCode loads a nested AGENTS.md when the agent explores its directory,
so the detail now lives beside the code it covers.

The root keeps the always-relevant parts (hard rules, layout, conventions
and a verification block) plus a "Where to look" index; the signer, store,
UI, app core, data and build-aux notes moved to their own files. Section
IDs (M1-M12) and trap numbers are unchanged so cross-references still
resolve; the few "see X" pointers were repointed at the new file.
This commit is contained in:
raucao committed 2026-12-01 12:56:46 +04:00
1 parent 9cd4e9a282
commit fe7a164201
7 files changed
+1482 -1384

No files matched your search

+39 -1384
View File
File diff suppressed because it is too large. Load diff
+203
View File
@@ -0,0 +1,203 @@
# Regent — build, deploy and release tooling (`build-aux/`)
Moving a build to another machine, cutting a release, and the test
harnesses.
## 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-deploy` installs the
`.Devel` identity — `regent-devel` in `~/.local/bin`, its own desktop file, data
dirs and D-Bus name — so it runs *beside* a stable `/usr` install instead of
replacing it. The default profile is stable.
- **Only the stable build registers `x-scheme-handler/nostrconnect`.** The nightly
desktop file deliberately omits `MimeType` — system integrations belong to the
installed release — though the nightly still accepts a `nostrconnect://`
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 a `mimeapps.list` default even after the desktop file stops
claiming the scheme, so `repair_scheme_handler` drops 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.
- `--pkg` builds `build-aux/regent-dev/PKGBUILD`, which packages the working
tree and is a preview of the real release packaging. (The AUR recipes are
`build-aux/aur/{regent,regent-git}`; see "Releases".)
- The wrapper **updates itself**: it fetches `build-aux/regent-deploy.sh` from the
build host and re-execs when it differs (keeping the previous copy as `.bak`;
`REGENT_DEPLOY_NO_UPDATE=1` skips 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 says `Exec=regent` (or
`Exec=regent-devel` in a nightly build). `regent-deploy` rewrites the copy it
installs to the absolute `~/.local/bin/regent` (or `…/regent-devel`), because
GIO **drops a desktop file whose `Exec` does not resolve on the session's
PATH** — and GNOME Shell then refuses every notification from the app, silently
(see the notification section, src/ui/AGENTS.md). It checks the result and warns if the shell
still cannot resolve the app. The packaged file is left alone: `/usr/bin` is on
PATH.
## Releases
- **Three stages, split across two machines:
`build-aux/release.sh prepare|sign|publish <version>`.** The build host runs
`prepare` (bump, build, `meson dist`, and an **SSH-signed** release commit);
the laptop runs `sign` (**GPG**: the tag and a detached tarball signature) and
`publish` (Gitea via `gt release create`, the AUR, Nostr via
`ngit 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. `prepare` proves 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); `sign` refuses unless `HEAD` is the commit
`prepare` recorded in `dist/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`
(AUR `pkgver`). Do not "simplify" one of them — `appstreamcli vercmp` and
`vercmp` both disagree with the semver spelling.
- **Release notes live only in `CHANGELOG.md`.** The metainfo `<releases>` block
is generated from it by `build-aux/gen-metainfo-releases.py` (between the
`releases:begin`/`releases:end` markers); never hand-edit the block.
- **The AUR recipes are `build-aux/aur/{regent,regent-git}`** — the stable
tarball package and the VCS one. `publish` fills `pkgver`/`_tag`, the real
sha256, and the signing fingerprint (`validpgpkeys`, with the `.asc` in
`source`), then pushes to `aur.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 `--pkg`
builds, not an AUR one.
- **Every PKGBUILD sets `options=('!lto')`.** makepkg's default `lto` appends
`-flto=auto` to `CFLAGS`, and `ring`/`secp256k1-sys` compile their C through
`cc` (which honours `CFLAGS`). rustc links the final binary without `-flto`, so
GCC's LTO plugin never runs and `lld` reports every C symbol as undefined
(`undefined symbol: rustsecp256k1_v0_10_0_…`) — the AUR build fails while a
plain `cargo`/`regent-deploy` build on the same machine links fine. `!lto`
only turns off makepkg's *C-flag* LTO; Rust's own `lto = true` stays.
- **Nostr is a mirror.** `.ngit/release.yaml` publishes 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) runs `cargo test --locked`,
`cargo clippy --all-targets --locked -- -D warnings` and `cargo deny check`
(`deny.toml`). The job runs on the **`regent-ci` runner**, whose label maps to
the image built from `build-aux/ci/Dockerfile` (`build-aux/ci/build-image.sh`
builds and pushes it to the Gitea registry), so the workflow installs nothing.
The image is **Arch-based** because Regent's `v4_24`/`v1_10` crate features
want GTK ≥ 4.23 / libadwaita ≥ 1.10 — newer than the latest stable GNOME
release (GNOME 50 ships GTK 4.22), so the old `ubuntu-latest` job and the GNOME
OS SDK both fail the build. The toolchain is pinned **in the image** (1.99.1)
because the `-D warnings` gate is calibrated to a compiler, and `cargo-deny`
fetches 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 in `src/signer/AGENTS.md`:
```sh
CARGO_TARGET_DIR=_build/cargo-target REGENT_TEST_RELAY=wss://nostr.kosmos.org \
cargo test --release -- --ignored --nocapture nak
```
The `nak_*` 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 own `nak serve` on 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_request` with a client key they control (denial, allow-always per kind,
encryption and decryption both remembered, a silent answer logged as
`allowed-silently`, the rate limit, a dropped
question denying, revoking a permission bringing the prompt back, `logout`
forgetting 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, and `record` trims an
oversized file while keeping it 0600. All run on a plain `cargo test`.
- The **manual re-fetch's outcomes** are pinned by the ignored
`nak_the_outbox_relay_profile_wins`: `Updated` for a newer profile from the
directory and from the identity's own relays, `UpToDate` when the relays answer
with what is already held, and `NotFound` for a key nobody publishes. The three
toast texts are a unit test in `ui::keys_view`.
- The **NIP-05** logic is pure and covered offline: parse (every rejecting shape,
including empty labels, ports, paths and schemes), the `.well-known` URL
(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 ignored
`nip05_of_a_real_domain_is_verified`: set `REGENT_TEST_NIP05=user@domain` and
`REGENT_TEST_NIP05_KEY=<hex>` (written against `raucao@kosmos.org` and the key
the About dialog links to) and run `cargo 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.json` is 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 with `locked` in the log (never `allowed-silently`) — plus a responder
test that a silent UI never unlocks.
- `store::profiles::tests::nak_the_outbox_relay_profile_wins` (ignored, needs
`nak` and 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, needs `nak`) 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 when `REGENT_TEST_RELAY` is set.
- End to end (vault → responder → app), in a throwaway HOME:
```sh
dbus-run-session -- build-aux/acceptance.sh
```
Seeds a NIP-49 `keys.json` (and checks it holds no plaintext identity key and
is mode 0600), runs a `nak` loopback 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 (a `nak req --stream`
subscriber must be listening, or `nak serve` mutes the response), and that a
waiting prompt raises a notification. Needs `nak`, `gtk4-broadwayd`, `python3`
with `dbus-python` (for `build-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 the `gtk` path 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_LOG` and simulates a click the way each backend expects:
`ActivateAction("focus")` on the app for the gtk path (what GNOME Shell does),
an `ActionInvoked` signal for freedesktop. Gotchas there: `dbus.service.BusName`
and 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_connection` raises, so each interface needs
its own class), and `str()` on a `dbus.Byte` is the raw character. The request
itself is hand-built — an approved client is seeded in `apps.json` and
`nak encrypt` + `nak event` publish the `kind:24133` request, 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-deploy` installs it and `Gio.AppInfo` must index it,
and a copy with an unresolvable `Exec` must 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).
+45
View File
@@ -0,0 +1,45 @@
# Regent — build metadata and UI resources (`data/`)
The `.desktop`, metainfo and GSettings templates, the app icons, and the
Blueprint sources under `data/resources/ui/`.
## Blueprint / Meson traps
1. 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 get `error: Unexpected tokens`.
2. Meson forbids a **path segment in a `custom_target`'s `output`**, and
`batch-compile OUTPUT SOURCEDIR FILES…` preserves paths relative to
`SOURCEDIR` — so the tempting `output: 'ui/window.ui'` fails outright
("Output … must not contain a path segment"), and the `output: '.'` 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 `.ui` is a
real file output; the resource paths are then the plain file names
(`/org/kosmos/raucao/Regent/window.ui`).
3. The app aborts at startup with `Settings schema … is not installed` unless dev
runs set `GSETTINGS_SCHEMA_DIR=_build/data` (see the run recipes in
`README.md`).
## Validation commands
```sh
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`:
```sh
GSETTINGS_SCHEMA_DIR=_build/data REGENT_GRESOURCE=… ./_build/regent
```
+258
View File
@@ -0,0 +1,258 @@
# Regent — app core (`src/`)
The windows, the always-on process, the headless runner and the
cross-cutting code in `src/*.rs`. The subsystems it wires together live
beside it: `src/signer/AGENTS.md`, `src/store/AGENTS.md`,
`src/ui/AGENTS.md`.
## Windows and first run (M10)
- **Two windows, one `AppState`.** `window.rs` builds both and holds the
`Windows` registry; the identities window is chrome
(`data/resources/ui/keys.blp`) around the existing `KeysView`. A second
`AppState` would mean a second registry and a second signer on one device key
(see M5, src/store/AGENTS.md), so the registry is created once in `application.rs` and shared. The
window is 460×560: tall enough for the **first-run empty state** and the
add/import dialog forms, because GTK never resizes a mapped window, so the
default has to fit the tallest thing it shows. The **width is deliberate**: it
is above libadwaita's bottom-sheet threshold (`AdwDialog`'s `auto` mode uses a
bottom sheet when the window is `max-width: 450px or max-height: 360px` — see
`adw-dialog.c`), so every dialog parented to this window is a centered floating
card rather than a sheet docked to the bottom edge.
- **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` (a `state.listen` callback) 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 every `notify()`
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", and
`app.focus`, `app.lock` and `present_preferences` all go through it. Do not
reintroduce `app.windows().first()` — it is creation order — and note that
`app.focus` used 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 through `Windows::visible_parent()`
(`active_window()`, else `primary()`): an `AdwDialog` inside a hidden window is
silently invisible, so `present_preferences`/`present_about`/`present_connect`/
`pair_uri` must never parent to a window that is off screen.
- The identities window is created once and `set_hide_on_close(true)`:
`AppState::listen` cannot unregister and its closures capture widgets, so a
window destroyed and rebuilt would leave listeners pointing at dead widgets.
`present_identities` makes it **transient for the main window** while that is
visible: GNOME Shell's focus-stealing prevention shows a "<app> 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 an `AdwPreferencesDialog` — libadwaita
1.6 deprecated `AdwPreferencesWindow` in favour of it — built **once** and
re-presented (`AdwDialog` re-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 holds `config.relays` from start, the bunker URI advertises them
and `get_relays` serves them, so a mid-run edit would mean "changed, but not
until restart, and the paired clients were told otherwise". Reachable by
`Ctrl+,` 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
the `async` was vestigial from the removed keyring — so the launch decision can
depend on it and `state.store()` is no longer an `Option`. A vault that exists
but cannot be read is **fatal**: `application::run` prints and exits non-zero
*before* `app.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, default `ask`)
picks: `ask` shows an `AdwAlertDialog` (Cancel / Keep Running / Quit) with a
"Remember this choice" checkbox; `background` hides; `quit` ends 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_close` always returns `Propagation::Stop` — GTK must never
destroy the window — and the choice is only offered while
`SignerRunner::status()` is `Running`: 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 reaches
`close_request` at 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. `PrimaryHandle` is the main window plus one
`auto` flag: `present`/`hide`/`toggle` are user-initiated and clear it;
`present_for_prompt` presents a hidden window and sets it; the responder's
`Notice::RequestAnswered` calls `restore_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 when `present_question` returns
would flicker and strand the unlock dialog on a window it just hid.
- **Notifications still fire while hidden.** `notify_pending` runs *before*
`present_for_prompt`, so the user is away (the window is hidden) and a
notification goes out; a click lands on `app.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`), not `Activate`: the GNOME AppIndicator
extension waits out the double-click interval on every click when an `Activate`
method exists, so the menu-only interface is what makes it open at once.
It holds only `Send` state and talks to the main loop over an `async_channel`;
visibility/status/pending go back through a shared `Arc<Mutex<TrayModel>>` and
`Handle::update`. `show-tray-icon` (default true) gates it. A missing host
(stock GNOME without the AppIndicator extension) is **not** an error:
`watcher_offline` logs (once per offline event) and returns `true`, so the icon
appears the moment a host does. A start is asynchronous, so `tray_starting`
guards 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.Background` portal — hiding the window alone does not
list the app. `portal::request_background` is a hand-rolled `gio` D-Bus call
(not `ashpd`, which would pull a second zbus major in beside ksni's). Called
when hiding to the background and at startup when `autostart` is set.
`--background` starts with no window (the autostart `Exec`); the flag is
stripped from the argv GApplication parses.
- **`g_application_quit()` never emits `close_request`**, so the menu's Quit,
Ctrl+Q and the tray's Quit bypass the dialog with no "quitting" flag.
## Headless mode and CLI pairing (M6)
- `regent --headless` runs the signer with **no window** (and no display): it is
a plain tokio program, deliberately *not* a `GtkApplication`.
`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 `Deny`
immediately (not after the timeout). Pre-approve with "Allow always" in the
GUI, then run headless. `get_public_key`/`ping`/`get_relays` stay automatic.
- **CLI pairing is the client-initiated (`nostrconnect://`) flow**: parse the
URI, subscribe to the client's relays (kept in `SignerConfig::extra_relays`,
**not** in `config.relays`, so they never leak into the bunker URI or
`get_relays`), register the app, then send the `connect` **response** whose
`result` is the client's secret, p-tagged to the client and signed by the
device key. Running `--pair` is 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 in `argv` or history. The
`bunker://` query is percent-encoded with `url::form_urlencoded` (I3), so a
relay URL cannot smuggle a second query parameter. Client-supplied
relays are **`wss://` only and at most `MAX_CLIENT_RELAYS` (5)**, and a literal
IP that is not globally routable is refused — a `ws://` or `169.254.x`/loopback
relay would otherwise turn a hostile URI into a local-network probe. The
`REGENT_RELAYS` test override skips both checks (as it already lets a test point
the signer at `ws://127.0.0.1`); the relays that survive are shown in the
pairing dialog's Details.
- The responder answers `connect` with `"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 the
`bunker://` `config.uri`) are shared `Arc<Mutex<String>>`s; a successful **new**
pairing — the responder's `connect` arm after `approve`, and `pair_client` after
`complete_pairing` — calls `rotate_secret`, which mints a fresh 96-bit secret
and rebuilds the URI. So a copied/shoulder-surfed `bunker://` 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()` in `from_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 name `org.kosmos.raucao.Regent`, so `NameHasOwner` is 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`'s `startup` handler)
and headless (`headless::serve`) therefore take an **unconditional** exclusive
`flock` on `regent.lock` (mode 0600) through `instance::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 in `startup`, which GLib emits only for the
primary instance, so a secondary forwarding a `nostrconnect://` link still
reaches the primary; a refused instance also short-circuits `activate`/`open`,
because `quit()` alone does not stop them being emitted. The kernel drops the
lock on exit, so it cannot go stale.
- Errors are loud: `--headless`/`--pair` print 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
via `take(4097)` into a `Zeroizing` buffer, and never logged. Without it
a locked vault simply denies the sensitive methods. `--pair` needs 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 serialized `Approver` queue
(`Approver::ask_pairing`; L4). On allow, the client's relays are
added to the running signer and `signer::pair_client` registers + answers. If
the signer is stopped, it is started with the client's relays first. The
`SignerRunner` has a `Stopped | Starting | Running` state 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_error` therefore falls back to
`Windows::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's `nostrconnect://` handler (see dev deploy, build-aux/AGENTS.md).
- **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 in `pair_now`; the bunker-URI direction
has no code path in the dialog at all — the client connects from outside — so
`ConnectDialog` snapshots the current identity's app count on `present()` and
closes when the registry grows past it (the `changes` ping `record()` 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_relays` mirrors `start`: add with
`verify_subscriptions`, **wait until connected**, then subscribe an explicit
`(RelayUrl, Vec<Filter>)` target. Subscribing before the connection lands is
trap 2 again (src/signer/AGENTS.md), 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** plus `config.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 sends `connect` immediately, which
a new client cannot do without the bunker secret.
- **Known limitation:** a manual stop/start drops the client's relays
(`extra_relays` are per-run). Spec-compliant clients recover via
`switch_relays`; others need re-pairing. Persisting per-app relays in
`apps.json` is 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 `.service` file + `DBusActivatable`).
## Verified API traps (do not rediscover these)
> Numbering is global across the three `Verified API traps` lists (here, `src/signer/AGENTS.md`, `src/ui/AGENTS.md`); only the traps relevant to this area are listed.
1. The crate is `gtk4` but must be aliased: `gtk = { package = "gtk4", … }`.
11. A `match` **scrutinee** is a temporary scope that lasts to the end of the
match, so `match self.cell.borrow().clone() { … None => *self.cell.borrow_mut()
= … }` panics with "RefCell already borrowed" — the `Ref` is still held. Bind
the clone to a local first (`let existing = self.cell.borrow().clone();`) and
match on that. An `if` **condition** is its own temporary scope, so the
`if self.cell.borrow().is_none() { *self.cell.borrow_mut() = … }` form in
`Windows::build` is fine. This bit `present_preferences` on the first click;
the acceptance test now activates `app.preferences` twice over D-Bus for it.
+139
View File
@@ -0,0 +1,139 @@
# Regent — the NIP-46 signer (`src/signer/`)
The responder in `src/signer/mod.rs`, the approval bridge in
`src/signer/approval.rs` and the rate limiter in `src/signer/policy.rs`,
plus the parts of `src/state.rs` and `src/runner.rs` that drive them.
## The signer (NIP-46)
- Requests arrive as `kind:24133` events 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-shaped `sign_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 a `connect` with 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 in `apps.json`
but **every sensitive request is still put to the user** — `sign_event`,
`nip04/nip44_encrypt` and `nip04/nip44_decrypt` — **until the user grants
"always" for it** (the policy model below). `get_public_key`, `get_relays`,
`switch_relays` and `ping` stay 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 stall `ping`, `get_public_key` or an
auto-approved signature behind it. The `Approver`'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 `Permission` on the app in `apps.json`: for `sign_event` an allow-list
of **kinds**, for encryption and decryption a **method name**. A request
covered by a stored permission is answered without asking — subject to the
rate limit below.
- **Decryption can be granted (2026-12-01).** It is the most consequential grant
— the ciphertexts already sit on relays, so "always" reaches history the
application was never asked about — but refusing to remember a yes made a chat
client re-read its history one prompt per message, which trains the user to
click through the prompts that matter. So `Decrypt` now stores a
`Permission::Method` like an encryption (per application, per method) and the
dialog offers Deny / Allow once / Allow always. Three things keep it honest:
the dialog carries an **above-the-fold banner** spelling out the scope (every
peer, and older messages fetchable from any relay — `request_warnings`); the
grant is deliberately **not** peer-scoped, because a NIP-17 gift wrap is
signed by a fresh ephemeral key per message, so a peer-scoped rule would match
only the inner seal and still prompt for every wrapper; and the rate limit, the
activity log (`allowed-silently`), the per-permission *Remove* row and the
immediate effect of revocation all still apply. The vault gate is unchanged: a
granted decrypt on a locked vault still raises the unlock prompt, and in
headless a locked vault still denies.
- **The rate limit bites a history sync.** `auto-approve-limit` is per app across
all silent answers, and a NIP-17 DM costs two decrypts (wrap + seal), so a sync
past roughly half the limit — default 30/min, so ~15 messages — asks again.
That is the runaway backstop working as designed; the user can raise it in
Preferences. Accepted and documented rather than special-cased.
- **NIP-04 is flagged (I2).** A `nip04_encrypt`/`nip04_decrypt` request adds an
above-the-fold banner saying NIP-04 is the older, unauthenticated scheme and
NIP-44 is recommended (`request_warnings`, comparing the `nim_name` form
`"nip04"`).
- **Rate limit.** `signer::policy::RateLimiter` caps silent answers per app:
`auto-approve-limit` requests 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 live `Arc<AtomicU32>` view of the setting, shared with the running
signer (`AppState::auto_approve_limit`; a `connect_changed` handler keeps it in
step), so setting it to 0 stops silent answers **immediately** — no stop/start,
and an external `gsettings set` is honoured too. The handler is installed on
the `gio::Settings` instance `AppState` holds for the process: it is owned by
that GObject and would die with it, and a bare `SignalHandlerId` keeps nothing
alive.
- **Replay and freshness (H1).** `kind:24133` is 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 before
`handle_request`, drops a wrapper event whose `created_at` is more than
`REQUEST_FRESHNESS` (120 s) from now, one minted before this run started, and
any event id already seen (bounded by `SEEN_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 is
`wss://nostr.kosmos.org` because **many public relays reject or rate-limit
`kind: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** write `apps.json`; `authorize_inner`
re-checks `identity_for` (and, for a silent answer, `permits`) after the last
`await` — 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 and `nostrconnect://`-link pairing dialogs go through the same
`Approver` queue (`Approver::ask_pairing` → the `Prompt::Pair` arm in
`ui/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 `Filter` is 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 against `nak serve`,
hangs against a real relay.)
- **Wait for the relay to be connected before subscribing.** A REQ sent while
a relay is still `Pending` is registered locally but never transmitted.
Localhost connects instantly, so this only shows up on `wss://`. We use
`add_relay(…).verify_subscriptions(true)` (which also re-sends the REQ after
a relay reconnects — essential for an always-on signer) plus
`connect().and_wait(…)`.
- 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.
## Verified API traps (do not rediscover these)
> Numbering is global across the three `Verified API traps` lists (here, `src/signer/AGENTS.md`, `src/ui/AGENTS.md`); only the traps relevant to this area are listed.
2. `EventBuilder` has no finalize method in `nostr` 0.45; build
`UnsignedEvent::new(pk, ts, kind, tags, content)` and call
`signer.sign_event(unsigned)`.
3. rust-nostr's typed `NostrConnectMessage`/`NostrConnectRequest` cannot parse a
spec-shaped *unsigned* `sign_event` (it wants a full event with
`pubkey`/`id`/`sig`). Hand-parse the `{id, method, params}` envelope.
4. Clients send `switch_relays` *before* `connect`, sometimes with
`params: null` (not `[]`). Handle it, and tolerate null params.
5. `NostrConnectUri::parse()` handles `bunker://` (`is_bunker()`, `relays()`,
`secret()`) — use it for the **signer-initiated** direction. For
`nostrconnect://` it expects a **non-standard `metadata=<json>`** query
parameter, so a spec-shaped URI (`relay`/`secret`/`name`/`url`/`image`/
`perms`) fails to parse: hand-parse the client direction (see
`signer::parse_client_uri`).
6. Requests arrive NIP‑44 encrypted; fall back to NIP‑04 for legacy clients.
Respond NIP‑44.
+541
View File
@@ -0,0 +1,541 @@
# Regent — storage (`src/store/`)
The key vault, the approved-application registry, the activity log, cached
profiles and avatars, and NIP-05 verification.
## Apps, permissions and the activity log (M5)
- `apps.json` is the single source of truth for what an app may do without
asking, and it is **shared**: `AppState` owns one `Arc<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 `AppState` once per process** (in `application.rs`, captured by the
activate closure), not per window. A second `AppState` would mean a second
registry and a second signer on the same device key.
- The Apps page shows one `AdwExpanderRow` per app, with a per-app `view-more`
menu as its only suffix (*Rename…* and *Revoke*), one *Remove* row per stored
permission (kind for `sign_event`, method for encryption or decryption), and
*Forget all*.
The list is **newest approval first** (`list_for` sorts by `approved_at`,
descending, ties in reverse insertion order), so a re-pairing moves an app back
to the top and pre-`approved_at` entries (timestamp 0) sit at the bottom.
`apps.json` still 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 own `label` first, 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.label` is the user's own name for it,
deliberately separate from the client's `name`: `approve` rebuilds the entry on
every pairing, so a label kept in `name` would be lost the next time a
metadata-less client reconnects. `App::display_name()` prefers the label, and
`AppRegistry::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, and `approve` preserves an existing label when
the dialog collected none.
- The activity log (`store/audit.rs`) records **metadata only**: app, method,
event kind, outcome, time. `Entry` has a typed `kind: 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. Both
`activity.jsonl` and `apps.json` are 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 from `record()`
and registry mutations, and `try_send` never 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.json` is written **atomically** (temp file + rename), and a corrupt one
is moved to `apps.json.corrupt` rather 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_permissions` is a
**Regent extension**, not NIP-46; the requested `perms` from a `connect`
(`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*
(GSettings `current-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::approve` only 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`/`Many` for tests, `Store(Arc<KeyStore>)` in production).
The responder opens the vault **after** the approval, just before signing.
- `AppState::refresh_identities` resolves 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
entry `put_relay_list` created only for its attempt clock, is *not* an update:
"updated" means the name, picture or *declared* address changed — a NIP-05 verdict
arrives later, from `ensure_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 than `kind0_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 an `AdwActionRow` title plus subtitle. In-app pairing uses the
current identity and warns when it would rebind an existing app.
- Headless: `--headless`/`--pair` take **`--key <npub|hex>`** (default: the
current identity). Serving resolves per app, so headless needs no single
"active" key.
## Profiles, avatars and NIP-05 (M7b)
- **Profiles** (`store/profiles.rs`): kind-0 is fetched best-effort and cached in
`profiles.json` (0600). Discovery goes through a **directory set** —
`PROFILE_RELAYS` (`wss://directory.yabu.me`, `wss://purplepag.es`,
`wss://profiles.nostr1.com`), overridable with `REGENT_PROFILE_RELAYS`, else
`REGENT_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 an
`authors` query tells them which identities this machine holds. The set is
measured, not guessed (2026-11-29, 20-key sample; full data in the plan's
`relay-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_targets` therefore emits one filter per relay, one author
ever; in `nostr-sdk` that means one `subscribe`/`fetch_events` call per identity
(`RelayPool` generates **one** `SubscriptionId` shared by every targeted relay,
and reports success as `HashMap<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 **no `limit`**:
`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_CAP` 5 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, src/signer/AGENTS.md). 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 two
`CONNECT_WAIT`s plus two `WAVE_CAP`s (~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 one `consider` merge
that drops authors nobody asked for and any `created_at` more than 5 minutes in
the future (`FUTURE_SLACK`) — that is what keeps a relay from pinning a
watermark out of reach.
- **`profiles.json` holds the outbox and its clocks**, written by three
single-owner writers: `put_metadata` (kind-0, older refused — see below — sets
`kind0_at`/`fetched_at`), `put_relay_list` (sets `write_relays` only from a
*strictly* newer kind-10002 — `created_at = 0` means "nothing found" and only
moves the clock, so a transient miss cannot wipe a working outbox — and always
sets `relays_checked_at`), and `note_recovery`.
- **`put_metadata` accepts an equal `created_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 to `Profile` after the entry was written be filled
in — `nip05` arrived 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 advances
`fetched_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 stale `fetched_at`, so `needs_refresh` stayed true and
the app re-fetched it on **every start**. An *older* version is still refused,
which is the whole point of the watermark. Equal `created_at`s are settled by
the **lower event id** (NIP-01's rule for replaceable events) — in the merge map
*and* in the cache, which keeps `kind0_id` for 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 before `kind0_id`
existed adopts the next equal-`created_at` answer, which is also how a field added
later gets filled in. `put_relay_list` deliberately stays strict: its
attempt clock advances on every call anyway, so nothing can be stranded there.
`RELAYS_TTL` is **7 days** on *attempts*, so an identity that publishes no 10002
is re-discovered weekly, not on every start; `RECOVERY_BACKOFF` is 1 day on the
directory kind-0 fallback, which matters because a missing profile never
advances `fetched_at`, so
`needs_refresh` stays 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 ignored `nak_the_outbox_relay_profile_wins` test covers the
cross-relay newest-wins rule, two identities and the warm path (dead directory,
cached outbox) against two local `nak serve`s on ports 10590/10591.
- `display_name`, `picture` and a **well-formed** `nip05` are kept — nothing else.
`picture` is bounded like `ClientInfo.image` (trimmed, ≤256 chars, blank ⇒
absent) and re-bounded on read, because `profiles.json` is on disk; an `nip05`
is 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's `nip05` is
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 is `Profile.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_nip05` compares 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::Image` being 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 `IconStore` as app icons (https/inline `data:` only, pinned public
addresses, ≤3 re-validated redirects, 1 MiB, magic-byte raster gate — see
M11). `AppState::ensure_avatars` is the single "make avatars show" call, from
`refresh_identities` and from the profile fetch's completion; it hydrates the
cached picture and fetches the rest. **Not gated by `load-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_label` is the single display rule: profile `display_name`
first, 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-value`
class (`plain::key` for labels we build, `plain::key_row` for a row whose
*subtitle* is the key). Deliberately **not** libadwaita's `.monospace`: that one
also switches to the code size and, on an `AdwActionRow`, takes the title with
it — hence the two descendant selectors in `data/style.css` (one for
`AdwActionRow`, one for `AdwExpanderRow`, whose header sits deeper), mirroring
libadwaita's own `row.property.monospace`. Widths: the 31-character
`shorten_npub` cut 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 no `Identity 3` default
and the import dialog has no `Imported 1`. Import carries a `Name` field that is
**prefilled from the cached profile** as soon as the pasted string decodes to a
key (`prefill_name`: `nsec`/hex; an `ncryptsec`'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_label` prefers the profile at display time only, so a key
imported before its profile was known simply gets its name when the fetch
lands — `refresh_identities` fetches 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 through `notify`,
which rebuilds the list (and re-sorts it by the new name); the `changes` pings —
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).
## The key vault (M8)
- **One file, `keys.json`**, at `glib::user_data_dir()/org.kosmos.raucao.Regent/`
(mode **0600**, written atomically to a **unique** `tempfile::NamedTempFile`
and renamed over the target, a corrupt file moved to a timestamped
`keys.json.corrupt.<secs>.<nanos>` so a second corruption does not erase the
first). It holds `version`, an optional plaintext `device` nsec, an optional
`verifier` (present **only while the vault has no keys** — see the first-run
bullet below), and `keys: [{pubkey, name, ncryptsec}]`. A `version` **above 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. (The
verifier did **not** need a version bump: serde ignores the unknown field, so an
older Regent reads a verifier-only vault as empty — it can then set a fresh
passphrase and drop the verifier, which loses nothing because there were no
keys. Accepted.) There is **no Secret Service and no
`oo7`** dependency: 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 shared `store::create_private_dir` (L6), not with the process umask.
- **Vault mutations are serialized (M9).** `add_user_key`, `set_passphrase` and
`change_passphrase` hold a `tokio::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 a `std::sync::Mutex`
(`save_lock`, never across an `await`) across read-clone → write → rename, and
the temp file is unique, so concurrent saves cannot collide on a shared
`keys.json.tmp`. (`profiles.json` uses the same unique-temp write.)
- **Identity keys are NIP-49 `ncryptsec`** (`log_n = 16`, rust-nostr's
`MAX_LOG_N = 18` caps a tampered entry), all under **one global passphrase**.
The `pubkey` is stored beside the ciphertext so `list_user_keys` and the
signer's `get_public_key` work **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: with `keys.json` readable 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 at `log_n` 16) on
every request — a 100-event burst would be ~7 s of one core.
- **The first-run onboarding sets the passphrase before any key exists**, which is
what the optional `verifier` is for. `set_passphrase` (the "Set a passphrase"
step, and its keyless "Reset passphrase…" — the reset is allowed only while no
key is stored, where it loses nothing) encrypts a **fixed public constant**
(`VAULT_VERIFIER`, a 32-byte `SecretKey` because `EncryptedSecretKey::new`
takes one) under the passphrase and stores the `ncryptsec1…` string, then opens
the session through the ordinary `unlock`. `has_vault()` is
`verifier.is_some() || !keys.is_empty()`; `verify_passphrase` checks the first
**key** if one exists, else the **verifier**, else returns `Ok` (that last is
load-bearing for `generate_user_key` on a scratch store / headless, and
unreachable in the UI). `unlock` with no keys verifies the verifier, so a wrong
passphrase still fails. `add_user_key` **clears the verifier** as it stores the
first key: with a key, the key is the ground truth and the on-disk shape is
byte-for-byte the pre-onboarding one. A malformed verifier is dropped on load
(logged, not fatal) so the reset path stays reachable.
- **`add_user_key` verifies the passphrase** against the verifier or an existing
entry before writing, so a typo cannot quietly create a second passphrase that
opens only the new key. `change_passphrase` needs only the *new* one (we hold
the keys), re-encrypts every entry, and **re-encrypts the verifier too** when
one is present — its plaintext is the public constant, so this needs no old
passphrase, and without it the change would be a silent no-op on a keyless
vault. `rename`/`forget` need no passphrase at all.
**The unlocked vault is the authorisation (L3):** both `change_passphrase` and
`export_user_key_encrypted` refuse 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 s `glib` timer in `state.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
with **`CLOCK_BOOTTIME`** (`store::keys::boottime`), not `Instant`, because
`CLOCK_MONOTONIC` stops while the machine is suspended — a laptop that slept
through the timeout must still lock on resume. `boottime` is the **one `unsafe`
call in the tree** (a `libc::clock_gettime`). The vault also locks immediately
on **suspend** (`org.freedesktop.login1` `PrepareForSleep` on the system bus)
and on the **screen locking** (`org.gnome.ScreenSaver.ActiveChanged` on 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's
`non_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|decrypt` are decided first (a stored permission,
or a dialog), and only then — if the vault is locked — does `Prompt::Unlock` go
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`, `logout` and `switch_relays` never touch the vault and keep
working while locked.
- **Audit fidelity:** `authorize()` opens the vault **before** `record()`, so a
request the vault refused is logged as `locked` and never as `silent`/`allowed`
— the log must not claim an answer that was never produced. Never reintroduce
a `keys.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-lock `ComboRow` and a
lock row that **toggles with the vault's state**: unlocked it offers "Lock",
locked it offers "Unlock…" through the same `present_unlock` dialog the header
button uses — which is what lets a locked user reach "Change…" without leaving
Preferences. It is inert until a passphrase exists (a key, or the first-run
onboarding's verifier). **The identities window's first-run empty state is a
"Set up your vault" step** (`present_setup`, passphrase + confirmation) whose
only action sets the passphrase; the page only offers Create / Import once
`has_vault()` is true, and those dialogs then carry a **single** "Vault
passphrase" row (no confirmation — there is nothing to set, only to check, and
retyping it when the first key is added is the point). A quiet "Reset
passphrase…" on that keyless page reopens the same setup dialog (the store
allows an overwrite while no key is stored). 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 pure
`validate_passphrase` is unit-tested), so an accidental empty submit cannot
encrypt a key under `""`. The import key field is an `AdwPasswordEntryRow`
(masked), so a pasted `nsec` is not shown in cleartext. `plain::copy_secret`
copies an exported `ncryptsec` or a `bunker://` string and clears the
clipboard again after 60 s **if it still holds that value**.
- **The passphrase forms are action dialogs, not alert dialogs (HIG).**
`present_setup` / `present_create` / `present_import` are plain `AdwDialog`s
with a header bar, a bottom bar (Cancel + a suggested action) and an
`AdwToastOverlay`, because **an `AdwAlertDialog` always closes when a response
is activated** — the old forms vanished and opened a second "Something went
wrong" modal on a bad passphrase, with no way to keep them open. The action
starts **insensitive** and is re-evaluated on every keystroke
(`PassphraseFields::review`), which also marks the offending row with
libadwaita's `.error` validation class, so a too-short or mismatched passphrase
can never be submitted and needs no error message at all. Only an error that
cannot be known in advance — a wrong vault passphrase — is shown, as a **toast
inside the dialog** (a window toast would sit behind the dialog's scrim);
`AdwToast` renders markup by default, so it is built with `set_use_markup(false)`.
Return activates the action (`AdwDialog:default-widget` + the rows'
`activates-default`); `connect_closed` wipes the fields, and a failed submit
keeps them (L5). Do not "simplify" these back to `AdwAlertDialog`.
- **Never log, print or put the passphrase in argv/env.** The passphrase is
`Zeroizing` where 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 / pasted `nsec` in
`Zeroizing` before the async call (L5) — still hygiene, not a blanket
guarantee. Verified: on drop,
`nostr::SecretKey` calls secp256k1's `non_secure_erase()`, a volatile overwrite
— *not* a guarantee (copies can survive in registers or on the stack, and there
is no `ZeroizeOnDrop` contract). 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 not `Send`, so a
closure passed to `MainContext::invoke` cannot capture widgets — that is why
results come back over a channel instead.
## 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. `fetch` is the icon entry point and keeps the inline
`data:` support.
- `store::icons` (`IconStore`) owns the disk cache and the decoded textures. Files
under `glib::user_cache_dir()/…/icons/`, keyed by the client pubkey (validated
64-hex at the store boundary — `apps.json` is 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). One `reqwest` client **per
fetch** (`resolve_to_addrs` is baked in at build time, so a shared/`OnceLock`
client could not carry the pin).
- **The `.url` sidecar is the retry rule.** `needs_fetch` is true only when the
sidecar URL is missing or ≠ the app's `image`. 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 next `changes` ping. Do not
reintroduce "no icon file ⇒ fetch": `changes` fires on every answered request,
so that is an unbounded background loop and a multiplied presence leak.
- **Hardening (all of it mandatory).** `https` only (plus inline
`data: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 with
`tokio::net::lookup_host` and refuse any non-public address — IPv4 rejects
loopback, private, link-local, CGNAT `100.64/10`, `0.0.0.0/8`, `192.0.0/24`,
`198.18/15`, reserved and multicast; IPv6 is **allow-listed** to global unicast
`2000::/3` minus `2001::/23`, `2001:db8::/32`, `2002::/16` and `3fff::/20`
(which also refuses IPv4-compatible `::/96`, IPv4-translated, NAT64
`64:ff9b::/96`, ULA `fc00::/7`, link-local and discard ranges; IPv4-mapped
`::ffff:0:0/96` is judged as its embedded v4) — fail closed on a mixed answer; pin the
validated addresses; follow ≤3 redirects manually, re-validating and re-pinning
each `Location` (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 an `HTTPS_PROXY`/`ALL_PROXY` would 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 (a
`Location:` can carry it). Stream the body
with a **1 MiB cap**. The format gate is **magic bytes**, not `Content-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 as `Vec<u8>` and `gdk::Texture::from_bytes` runs in the `then` (GTK is not
`Send`). A cached `.img` may be decoded synchronously on the first paint
(`AppState::hydrate_icon`), bounded by the byte cap; `IconStore` memoises 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_dimensions` parses the
container header (PNG IHDR / GIF screen / JPEG SOF / WebP VP8/VP8L/VP8X) and
anything over `MAX_ICON_DIMENSION` (1024², since icons render at 32 px) is
refused **before** `gdk::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-icons` is on**,
fetched through `AppState::preview_icon`, which is **memory only**: no disk cache
is written for an unapproved app **and the texture is not put in
`IconStore.textures`** (it is handed only to the dialog's `apply` closure), 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 show `plain::shorten_npub` and build
the `AdwAvatar` with `show_initials(false)` (libadwaita's generic glyph) — never
the strings `"(unnamed)"`/`"Unnamed application"` as initials, which rendered as
`"("`/`"U"`. Empty `name`/`url`/`image` (and `perms`) are treated as **absent** in
`parse_client_uri` and `client_info`: some clients always emit
`name=&url=&image=&perms=`, and `url: Some("")` otherwise produced an empty byline
instead of the npub fallback. Note the **bunker direction often carries no
metadata at all** — noStrudel's `fromBunkerURI` sends none — so this is normal, not
a parse failure.
- **Render.** A 32 px `adw::Avatar` prefix on the Apps `AdwExpanderRow`, 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.
- `gc` runs only on an actual Apps-page rebuild (revoke/forget/last-key-removed),
never per ping, and its live set is `AppState::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 `picture` is
fetched, cached and rendered exactly like an app icon (`ensure_avatars`,
`hydrate_avatar`/`load_avatar`/`show_avatar` in `state.rs`), which is why the
two are keyed by the same 64-hex namespace. The only differences: it is **not**
gated by `load-app-icons`, it is fetched at startup and on every profile
refresh rather than at consent time, and `show_avatar` hands 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 calls `IconStore::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_info` bounds `image` to 256 chars like `parse_client_uri` does — it
reaches `apps.json` and is now a fetch input.
+257
View File
@@ -0,0 +1,257 @@
# Regent — the interface (`src/ui/`)
The approval and pairing dialogs, the identity switcher, the Apps and
Activity pages, and the Blueprint they are built from.
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")`.
## Notifications and the approval deadline (M9)
- A prompt is an `AdwDialog` **inside** the window, so if the window is not
focused nothing tells the user. Every responder-driven prompt therefore also
raises a `gio::Notification` from the `install` drain in `ui/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_ALWAYS`
forces "away" for the acceptance test — `gtk4-broadwayd` reports the window
active even though no window manager can focus anything. Same kind of documented
test override as `REGENT_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 `logout`
removes an application, and nothing else tells the user, so the responder sends
a `Notice` through `Approver`'s separate `notices` channel, drained by
`ui::approval::install_notices`. A second channel keeps `Prompt` meaning "needs
an answer" and a one-way notice out of a drain that blocks in
`present_question` until the dialog is answered; the notice id (`"notice"`)
keeps it from replacing, or being withdrawn with, a prompt's notification. It
is raised **unconditionally** — the `user_is_away` gate 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 an `app.focus` action
that presents the window. Verified mechanism: GLib's freedesktop backend sends
`actions = ["default", ""]` and a `desktop-entry` hint; on a body click GNOME
Shell emits `ActionInvoked(id, "default")` and GLib activates the app action
**in-process** (the `org.gtk.Notifications` path would call
`ActivateAction("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 `AdwBanner` above the
fold — truncated content (against the responder's `CONTENT_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). Those banners carry
`.warning`, which `data/style.css` maps to a warning tint: `AdwBanner` is tinted
through its `--banner-color` variable (libadwaita mixes it 30% into the window
background), and `.warning` **alone** does nothing on a banner — it only
recolours the foreground, which the banner's inner widget overrides. 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 the
`Answer`. 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" use `plain::DIALOG_WIDTH` (480) so neither resizes as the user
moves between them — the approval dialog pins it with `plain::alert_width`,
because `AdwAlertDialog` ignores `content-width` (see trap 17).
- **The dialog owns the deadline, and it is absolute.** `ASK_TIMEOUT` (60 s) is
turned into an `Instant` **when the ask starts** and travels to the UI in the
`Prompt`; the dialog answers `Deny` and 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
answered `Deny` with no dialog and no notification. User-initiated flows
(in-app pairing, export's unlock) pass `None`.
- 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 — else `org.freedesktop.Notifications`
(0). **The gtk path refuses the notification unless GNOME Shell can resolve
`<app id>.desktop` in 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()` in `application.rs` is 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 `Exec` does not resolve.** It validates `Exec`
while parsing and discards the whole file, so the app never enters the index and
every notification is refused. That is why `regent-deploy` rewrites the
installed copy's `Exec` to 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 packaged `Exec=regent` is correct for a `/usr` install.
- `connect_activate` is **idempotent**: it presents the existing window instead of
building another. Activation arrives for a notification click and for launching
`regent` again, and a second window would share the state and show the same
dialog twice.
## The multi-identity UI (M7b)
- **Header identity switcher** (`ui/switcher.rs`, Fractal's account-switcher
pattern): a `GtkMenuButton` showing 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_name` or 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 the `Windows` registry **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. Past `plain::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 than
`plain::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's
`smaller` is ~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
`GtkButton`s and libadwaita bolds every button's text (`button { font-weight:
bold }`, no `.flat` exemption), which is exactly what the identity's *name*
should look like (700, measured with
`get_pango_context().get_font_description()`). The npub/NIP-05 beneath it is a
value and stays normal weight — `label.key-value` sets `font-family` **and**
`font-weight: normal` for that (the class beats the theme's element selector).
The avatar's initials are bold too, by libadwaita's own `avatar` rule.
- **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.
## Verified API traps (do not rediscover these)
> Numbering is global across the three `Verified API traps` lists (here, `src/signer/AGENTS.md`, `src/ui/AGENTS.md`); only the traps relevant to this area are listed.
7. Several **Adwaita** widgets render text as **Pango markup by default**:
`AdwAlertDialog` heading/body (`heading-use-markup`/`body-use-markup`) and
`AdwActionRow` title/subtitle (`AdwPreferencesRow:use-markup`).
`gtk::Label` does **not** (it defaults to plain). Feeding
markup-rendered widgets dynamic text breaks rendering on the first `&` (a
`bunker://…&secret=…` connection string shows nothing) and lets a client
inject formatting. Build them through `crate::ui::plain`
(`plain::row`, `plain::expander`, `plain::dialog`), which
turns markup off; put untrusted text in an `extra-child` of plain labels. **Order matters:** a builder that sets `title`/`subtitle` before
`use_markup(false)` parses them as markup while it is still on, so an `&`
warns even though `use_markup(false)` follows — set markup off first, then the
text (`plain` does this). Symptom: a row renders empty and GTK logs "Failed to
set text … from markup".
8. `GApplication::send_notification` has **two** backends, chosen by priority:
`org.gtk.Notifications` (100 — used whenever the name is owned, i.e. on any
real GNOME session) and `org.freedesktop.Notifications` (0 — the fallback).
The gtk payload is `AddNotification(app_id, id, a{sv})` carrying `title`,
`body`, `icon`, `priority` (`low`/`normal`/`high`/`urgent`) and
`default-action`; the freedesktop one is the classic `Notify(...)` with
`actions = ["default", ""]` and `desktop-entry`/`urgency` hints. **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_notification` becomes `RemoveNotification` / `CloseNotification`.
9. `gtk4-broadwayd` has **no window manager**, so `GtkWindow::is_active()` is
`true` for a window nothing ever focused. Any "is the user looking at this"
branch is therefore untestable under Broadway without a forced override — and
`GdkToplevel::state()` is empty there too.
10. **GIO validates `Exec` while parsing a desktop file and drops the file when
the program cannot be found** (`g_find_program_for_path` returns NULL →
`goto error`). The app then never appears in `Gio.AppInfo::all()`, GNOME Shell
cannot resolve it, and every notification from it is refused — silently. A
desktop file for anything installed outside `PATH` needs an absolute `Exec`.
12. `GtkHeaderBar`'s `pack_start` **appends** to the start box (left to right in
call order), but `pack_end` **prepends** to the end box — so the *first*
`pack_end` ends up rightmost. The main window puts every control on the left
with `pack_start`, laid out `[menu][identity switcher][lock] …` in call
order. Remember the prepend if a control is ever moved back to `pack_end`.
13. **Never use `PANGO_ELLIPSIZE_MIDDLE` for a long, space-less token** (an npub,
a `bunker://` URI). Pango pads an ellipsized line to fill its target width by
widening the *ellipsis glyph* (`pango/ellipsize.c` `fixup_ellipsis_run`,
commit `c754c4d6` / pango#24, "so ellipsized text doesn't vibrate"). With
`END` that space lands at the line's right edge (invisible); with `MIDDLE` it
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_uri` return a fixed `head…tail`
string, and the row's `set_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.
14. A shortened subtitle hides the full value, so carry it as a plain
`tooltip_text` (never `tooltip_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".
`AdwExpanderRow` is not an `AdwActionRow`, but that no longer matters: its
byline is shortened like any other subtitle instead of reaching into the
label to change its ellipsis mode.
15. A `GtkScrolledWindow`'s **natural height is 0** unless
`propagate_natural_height` is set, and `AdwDialog` sizes itself to its child's
natural height. So a dialog whose child is a scroller collapses to just its
header bar the moment an explicit `content_height` is removed — measured at
104px against 303px for the same content. `max_content_height` only 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.
16. **`AdwDialog` is 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. Set
`follows-content-size` to make it track the content — "if the content
resizes, the dialog will immediately resize as well". But that property
**ignores `content-width`/`content-height`** and 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.
17. **`AdwAlertDialog` ignores `content-width`.** It uses internal breakpoints,
and a breakpoint-using `AdwDialog` has **no minimum size** — its
`content-width` property does not drive the floating size (measured: a `560`
request still renders 300 px wide; the same value set after `present()` is
ignored too). A plain `AdwDialog` *does* honour it, which is why "Connect an
app" worked. Set `width-request` instead (`plain::alert_width`), which the
dialog honours exactly. Do not "simplify" it back to `content_width`.
18. **A field in a dialog swallows Return unless it opts in.** The `GtkText`
inside every `AdwEntryRow` (and inside `GtkEntry`) has its own Return
binding: it emits `activate` and consumes the event, and only calls
`gtk_widget_activate_default()` when `activates-default` is `TRUE` — which
defaults to `FALSE`. So a dialog whose `extra-child` field should submit on
Enter needs `set_activates_default(true)` on that field;
`set_default_response`/`AdwDialog:default-widget` alone do nothing while the
field has focus, and focus starts there (`adw_alert_dialog_grab_focus`
prefers the extra child). Symptom: the user types, presses Enter, nothing
happens. The `FormDialog` forms (`ui/keys_view.rs`) opt in on every row; the
`AdwAlertDialog` forms (unlock, rename identity/app, export, change
passphrase) must too — and do not add live validation to them to compensate,
the alert dialog has none.