Show app icons from NIP-46 metadata

Applications declare a name, URL and image in their pairing metadata; Regent
already stored the image but never rendered it. It now fetches, caches and
shows it as a 32px avatar on the Apps page and beside "Application" in the
approval dialog, with a "Load app icons" preference to turn fetching off.

The URL is attacker-controlled, so the new src/store/icons.rs is mostly a
security boundary: https only (plus inline data: URLs that never leave the
process), every resolved address must be public (loopback, private, link-local,
CGNAT, reserved, multicast and IPv6 ULA/mapped-v4 are refused, fail-closed on a
mixed answer), the validated addresses are pinned with a client per fetch
(resolve_to_addrs is baked in at build time, so a shared client could not carry
the pin), redirects are re-validated and re-pinned hop by hop, the body is
capped at 1 MiB, and only PNG/JPEG/GIF/WebP pass — by magic bytes, so an SVG is
rejected before it can reach the decoder. A `.url` sidecar records the URL last
attempted, so a failed icon is never retried on every change ping; the cache
lives in the XDG cache dir, keyed by the client key and mode 0600.

No fetch happens before consent: the approval dialog shows initials for a first
pairing and the cached icon only for an app the user already approved. The name
stays the identifier; the icon is decoration, never the sole identifier.

Adds reqwest (rustls-tls, no default features), base64, and tokio's net feature.
This commit is contained in:
raucao committed 2026-11-26 22:39:13 +04:00
1 parent f65d179392
commit 468d918bd3
15 files changed
+1320 -12

No files matched your search

+54
View File
@@ -38,6 +38,7 @@ src/store/apps.rs the registry of approved applications + their permissions
src/store/audit.rs the activity log (metadata only, mode 0600)
src/store/keys.rs the NIP-49 key vault (identity keys + the device key)
src/store/profiles.rs cached kind-0 display names (read-only)
src/store/icons.rs app icons: hardened fetch + disk cache (M11)
src/ui/approval.rs approval dialogs
src/ui/apps_view.rs the apps page (permission table + revoke)
src/ui/activity_view.rs the activity page
@@ -489,6 +490,59 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
`blueprint-compiler`, bundled into the GResource, and loaded with
`gtk::Builder` + `builder.object::<T>("id")`.
## App icons from NIP-46 metadata (M11)
- Applications declare an `image` (icon) in their NIP-46 metadata; it was already
parsed and persisted (`parse_client_uri`, `client_info`, `App.image`). M11 is
the fetch → cache → decode → render, and it is mostly a **security** feature:
the URL is attacker-controlled.
- `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); resolve with
`tokio::net::lookup_host` and refuse any non-public address (loopback, private,
link-local, CGNAT `100.64/10`, `192.0.0/24`, `198.18/15`, reserved, multicast,
IPv6 ULA `fc00::/7`, `::1`, mapped-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; 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.
- **No fetch before consent.** The approval dialog shows the icon only when it is
already cached (an already-approved app); a first pairing shows initials.
Fetching an unknown app's URL at the moment trust is decided is a tracking ping
to that app's server — the same rule as M9's no-client-text notification bodies.
- **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 `AppRegistry::client_keys()` — every pubkey
across identities. The page list is identity-scoped, so a live set taken from it
would evict other identities' icons.
- **Preference** `load-app-icons` (GSettings, default on) gates all fetching;
turning it off clears the in-memory textures and rebuilds to initials.
- `client_info` bounds `image` to 256 chars like `parse_client_uri` does — it
reaches `apps.json` and is now a fetch input.
## Conventions
- App ID everywhere: `org.kosmos.raucao.Regent`; GResource prefix
Generated
+340 -3
View File
@@ -79,6 +79,12 @@ dependencies = [
"web-sys",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -91,6 +97,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bech32"
version = "0.12.0"
@@ -289,6 +301,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.9.1"
@@ -300,6 +318,17 @@ dependencies = [
"cpufeatures 0.2.17",
]
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
name = "chacha20poly1305"
version = "0.10.1"
@@ -307,7 +336,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead",
"chacha20",
"chacha20 0.9.1",
"cipher 0.4.4",
"poly1305",
"zeroize",
@@ -756,8 +785,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
@@ -779,9 +810,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasm-bindgen",
]
[[package]]
@@ -1052,6 +1085,29 @@ dependencies = [
"itoa",
]
[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.10.1"
@@ -1067,6 +1123,65 @@ dependencies = [
"typenum",
]
[[package]]
name = "hyper"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3"
dependencies = [
"atomic-waker",
"bytes",
"futures-core",
"http",
"http-body",
"httparse",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.12",
]
[[package]]
name = "hyper-util"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
dependencies = [
"base64 0.23.1",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"httparse",
"hyper",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
]
[[package]]
name = "icu_collections"
version = "2.4.0"
@@ -1213,6 +1328,12 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "itoa"
version = "1.0.19"
@@ -1284,6 +1405,12 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "memchr"
version = "2.8.3"
@@ -1353,12 +1480,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7a55567533eb00df5a6e2855f229e2092f593ab67c97aff7521fdfe55cf0383"
dependencies = [
"aes",
"base64",
"base64 0.22.1",
"bech32",
"bip39",
"bitcoin_hashes 1.2.0",
"cbc",
"chacha20",
"chacha20 0.9.1",
"chacha20poly1305",
"faster-hex",
"opaquerr",
@@ -1575,6 +1702,62 @@ dependencies = [
"image",
]
[[package]]
name = "quinn"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror 2.0.21",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.3",
"rand_pcg",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.21",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -1623,6 +1806,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -1671,11 +1855,21 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_pcg"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "regent"
version = "0.1.0"
dependencies = [
"async-channel",
"base64 0.22.1",
"glib",
"gtk4",
"image",
@@ -1683,6 +1877,7 @@ dependencies = [
"nostr",
"nostr-sdk",
"qrcode",
"reqwest",
"serde",
"serde_json",
"tokio",
@@ -1690,6 +1885,44 @@ dependencies = [
"zeroize",
]
[[package]]
name = "reqwest"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.12",
]
[[package]]
name = "ring"
version = "0.17.14"
@@ -1704,6 +1937,12 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -1733,6 +1972,7 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"web-time",
"zeroize",
]
@@ -1753,6 +1993,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "salsa20"
version = "0.11.0"
@@ -1855,6 +2101,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sha1"
version = "0.10.7"
@@ -1955,6 +2213,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
dependencies = [
"futures-core",
]
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -2204,6 +2471,51 @@ version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-http"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags 2.13.2",
"bytes",
"futures-util",
"http",
"http-body",
"pin-project-lite",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
@@ -2223,6 +2535,12 @@ dependencies = [
"once_cell",
]
[[package]]
name = "try-lock"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.28.0"
@@ -2331,6 +2649,15 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "want"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -2411,6 +2738,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
+5 -1
View File
@@ -16,11 +16,15 @@ glib = "0.22"
url = "2"
nostr = { version = "0.45", features = ["nip04", "nip44", "nip49", "os-rng"] }
nostr-sdk = { version = "0.45", default-features = false, features = ["rustls-tls-webpki-roots"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal"] }
# App icons are fetched from attacker-controlled URLs, so the HTTP client is
# built per fetch with the validated addresses pinned (see `store::icons`).
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal", "net"] }
async-channel = "2"
serde_json = { version = "1", features = ["preserve_order"] }
serde = { version = "1", features = ["derive"] }
zeroize = "1"
base64 = "0.22"
qrcode = { version = "0.14", features = ["image"] }
image = { version = "0.25", default-features = false, features = ["png"] }
@@ -16,6 +16,11 @@
<summary>Auto-lock timeout</summary>
<description>How long the key vault stays open after it is unlocked, in seconds. Zero means never lock automatically. This is a hard timeout measured from the unlock, not an idle timer: request traffic must not extend it, or a chatty client would hold the vault open forever.</description>
</key>
<key name="load-app-icons" type="b">
<default>true</default>
<summary>Load application icons</summary>
<description>Fetch and show the icon an application declares in its pairing metadata, from the application's own server, after you approve it. Turning this off stops all icon fetches and leaves the initials in place.</description>
</key>
<key name="relays" type="as">
<default>['wss://nostr.kosmos.org']</default>
<summary>Relays</summary>
+2
View File
@@ -22,6 +22,7 @@ cargo_build = custom_target(binary_name,
output: binary_name,
input: files(
'Cargo.toml',
'Cargo.lock',
'src/main.rs',
'src/application.rs',
'src/config.rs',
@@ -34,6 +35,7 @@ cargo_build = custom_target(binary_name,
'src/state.rs',
'src/store/apps.rs',
'src/store/audit.rs',
'src/store/icons.rs',
'src/store/mod.rs',
'src/store/keys.rs',
'src/store/profiles.rs',
+12
View File
@@ -64,6 +64,18 @@ impl Config {
}
}
/// Whether Regent may fetch the icons applications declare in their pairing
/// metadata. Off means no network request is ever made for an icon.
pub fn load_app_icons(&self) -> bool {
self.settings.boolean("load-app-icons")
}
pub fn set_load_app_icons(&self, load: bool) {
if let Err(error) = self.settings.set_boolean("load-app-icons", load) {
eprintln!("regent: could not save the app-icon preference: {error}");
}
}
/// Relays Regent talks to. `REGENT_RELAYS` (comma separated) overrides the
/// setting, which is what headless tests and CI use.
pub fn relays(&self) -> Vec<String> {
+3 -1
View File
@@ -1100,7 +1100,9 @@ fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
public_key: *public_key,
name: field("name"),
url: field("url"),
image: field("image"),
// Bounded like the `nostrconnect://` path: this reaches apps.json, and
// an icon URL is a fetch input.
image: field("image").map(|image| bound(&image, 256)),
}
}
+68
View File
@@ -14,6 +14,7 @@ use crate::config::Config;
use crate::runtime;
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
use crate::store::icons::IconStore;
use crate::store::keys::{Error as KeyError, KeyRef, KeyStore};
use crate::store::profiles::Profiles;
@@ -35,6 +36,8 @@ pub struct AppState {
names: Arc<Mutex<HashMap<String, String>>>,
/// Cached kind-0 display names, read-only.
profiles: Profiles,
/// Cached application icons and their decoded textures.
icons: Rc<IconStore>,
listeners: RefCell<Vec<Listener>>,
change_listeners: RefCell<Vec<Listener>>,
/// The responder pings this after it changes the registry or the log.
@@ -57,6 +60,7 @@ impl AppState {
current: Arc::new(Mutex::new(Config::new().current_identity())),
names: Arc::new(Mutex::new(HashMap::new())),
profiles: Profiles::new(),
icons: Rc::new(IconStore::new()),
listeners: RefCell::new(Vec::new()),
change_listeners: RefCell::new(Vec::new()),
changes,
@@ -146,6 +150,70 @@ impl AppState {
self.profiles.clone()
}
/// The application-icon cache and its decoded textures.
pub fn icons(&self) -> Rc<IconStore> {
Rc::clone(&self.icons)
}
/// Decode an already-cached icon, on this (main) thread, so a first paint
/// shows it without a round trip. Bounded by the icon byte cap.
pub fn hydrate_icon(&self, key: &str, url: &str) {
let icons = self.icons();
if !icons.begin_hydrate(key, url) {
return;
}
if icons.texture(key).is_some() || icons.needs_fetch(key, url) {
return;
}
let Some(bytes) = icons.cached_bytes(key, url) else {
return;
};
match crate::store::icons::decode(&bytes) {
Ok(texture) => icons.set_texture(key, texture),
Err(error) => {
eprintln!("regent: ignoring a cached app icon: {error}");
icons.mark_failed(key, url);
}
}
}
/// Fetch an application's icon, decode it on the main loop, cache it and ask
/// the views to repaint. A no-op when it is cached, in flight, or the key or
/// URL is unusable.
pub fn load_icon(self: &Rc<Self>, key: &str, url: &str) {
let icons = self.icons();
if !icons.begin(key, url) {
return;
}
let state = Rc::clone(self);
let key = key.to_string();
let url = url.to_string();
let fetch_url = url.clone();
runtime::spawn(
async move { crate::store::icons::fetch(&fetch_url).await },
move |result| {
icons.end(&key, &url);
match result {
Ok(bytes) => match crate::store::icons::decode(&bytes) {
Ok(texture) => {
icons.store(&key, &url, &bytes);
icons.set_texture(&key, texture);
}
Err(error) => {
eprintln!("regent: could not decode an app icon: {error}");
icons.mark_failed(&key, &url);
}
},
Err(error) => {
eprintln!("regent: could not fetch an app icon: {error}");
icons.mark_failed(&key, &url);
}
}
state.notify_changes();
},
);
}
/// What to call an identity: its kind-0 `display_name` if one was fetched,
/// else the user's label for the key.
pub fn identity_label(&self, key: &PublicKey) -> String {
+10
View File
@@ -142,6 +142,16 @@ impl AppRegistry {
self.apps.iter().any(|app| app.public_key == hex)
}
/// Every client public key, across identities. Used to scope the icon cache:
/// the Apps page list is identity-scoped, so a live set taken from it would
/// treat another identity's apps as orphans and evict their icons.
pub fn client_keys(&self) -> Vec<String> {
self.apps
.iter()
.map(|app| app.public_key.clone())
.collect()
}
/// The display hints recorded for an approved application.
pub fn client(&self, public_key: &PublicKey) -> Option<ClientInfo> {
let hex = public_key.to_hex();
+701
View File
@@ -0,0 +1,701 @@
//! The cached icons an application declares in its NIP-46 metadata.
//!
//! The URL is client-supplied, so fetching it is the security-sensitive part of
//! this module: `https` only, public addresses only (resolved and then pinned),
//! a bounded body, and raster formats only. A refused or undecodable icon simply
//! falls back to the initials an `AdwAvatar` draws.
//!
//! Cache layout (`glib::user_cache_dir()/<app id>/icons/`, the directory 0700),
//! keyed by the client's public key:
//!
//! - `<hex>.img` — the bytes that decoded, mode 0600.
//! - `<hex>.url` — the URL last **attempted** (success *or* failure), mode 0600.
//!
//! The sidecar is what makes a changed `image` refetch, and what keeps a bad URL
//! from being retried on every change ping: the fetch is armed by the URL alone,
//! never by "there is no icon file". Keying by the public key keeps the filename
//! safe without a hash dependency.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use gtk::gdk;
use gtk::gdk::prelude::*;
use gtk::glib;
use crate::APP_ID;
pub type Result<T> = std::result::Result<T, String>;
/// A body larger than this is refused, streamed or inline.
pub const MAX_BYTES: usize = 1024 * 1024;
/// How many redirects to follow; every hop is re-validated and re-pinned.
const MAX_REDIRECTS: usize = 3;
/// Decoded textures larger than this are dropped. A backstop only: the byte cap
/// and the raster allow-list are the real limits.
const MAX_DIMENSION: i32 = 4096;
const TIMEOUT: Duration = Duration::from_secs(5);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
/// Whether this is a URL an icon may be fetched from at all.
///
/// `https` and inline `data:image/…` only. Everything else — `http`, `file`,
/// `gopher`, `blob` — is refused before any resolution happens.
pub fn is_fetchable(url: &str) -> bool {
if let Some(rest) = url.strip_prefix("data:") {
return rest.starts_with("image/");
}
match url::Url::parse(url) {
Ok(parsed) => parsed.scheme() == "https",
Err(_) => false,
}
}
/// Fetch the bytes for `url`.
///
/// Runs on the async runtime. `data:image/…;base64,…` is decoded locally and
/// never touches the network; an `https` URL is resolved, validated, pinned and
/// fetched with a bounded body.
pub async fn fetch(url: &str) -> Result<Vec<u8>> {
if let Some(rest) = url.strip_prefix("data:") {
return decode_data_url(rest);
}
let mut url = url::Url::parse(url).map_err(|error| format!("that is not a URL: {error}"))?;
for _ in 0..=MAX_REDIRECTS {
if url.scheme() != "https" {
return Err(format!("refusing to fetch a {} URL", url.scheme()));
}
let host = url
.host_str()
.ok_or("the URL has no host")?
.to_string();
let port = url.port_or_known_default().ok_or("the URL has no port")?;
let addrs = resolve_public(&host, port).await?;
// `resolve_to_addrs` is baked in at build time, so the *client* is what
// carries the pin — a shared, process-wide client could not. Building one
// per hop is fine: icon fetches are rare and not latency-sensitive.
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(TIMEOUT)
.connect_timeout(CONNECT_TIMEOUT)
.resolve_to_addrs(&host, &addrs)
.build()
.map_err(|error| format!("could not build an HTTP client: {error}"))?;
let response = client
.get(url.clone())
.send()
.await
.map_err(|error| format!("could not fetch the icon: {error}"))?;
if response.status().is_redirection() {
let location = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok())
.ok_or("the icon redirect had no usable Location")?;
url = url
.join(location)
.map_err(|error| format!("the icon redirect was unusable: {error}"))?;
continue;
}
if !response.status().is_success() {
return Err(format!("the server answered {}", response.status()));
}
if let Some(content_type) = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
{
if !content_type.starts_with("image/") {
return Err("the server did not send an image".to_string());
}
}
let bytes = read_capped(response).await?;
sniff_raster(&bytes)?;
return Ok(bytes);
}
Err("the icon redirected too many times".to_string())
}
/// Read at most [`MAX_BYTES`] from the response, aborting past it.
async fn read_capped(mut response: reqwest::Response) -> Result<Vec<u8>> {
let mut out = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|error| format!("the icon download failed: {error}"))?
{
if out.len() + chunk.len() > MAX_BYTES {
return Err("the icon is larger than 1 MiB".to_string());
}
out.extend_from_slice(&chunk);
}
Ok(out)
}
/// Resolve `host` and refuse unless every address is public.
///
/// Fail-closed: a name that resolves to a mix of public and private addresses is
/// refused whole, so a rebinding server cannot slip a private hop in beside a
/// public one.
async fn resolve_public(host: &str, port: u16) -> Result<Vec<SocketAddr>> {
let mut out = Vec::new();
let addresses = tokio::net::lookup_host((host, port))
.await
.map_err(|error| format!("could not resolve {host}: {error}"))?;
for address in addresses {
if !is_public(address.ip()) {
return Err(format!("refusing a non-public address for {host}"));
}
out.push(address);
}
if out.is_empty() {
return Err(format!("{host} resolved to nothing"));
}
Ok(out)
}
/// Whether an address is globally routable. Anything local, private, reserved or
/// special is refused.
pub fn is_public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => is_public_v4(v4),
IpAddr::V6(v6) => is_public_v6(v6),
}
}
fn is_public_v4(ip: Ipv4Addr) -> bool {
if ip.is_unspecified()
|| ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_broadcast()
|| ip.is_documentation()
|| ip.is_multicast()
{
return false;
}
let o = ip.octets();
// 100.64.0.0/10 carrier-grade NAT.
if o[0] == 100 && (o[1] & 0xc0) == 64 {
return false;
}
// 192.0.0.0/24 IETF protocol assignments.
if o[0] == 192 && o[1] == 0 && o[2] == 0 {
return false;
}
// 192.88.99.0/24 6to4 relay anycast (deprecated).
if o[0] == 192 && o[1] == 88 && o[2] == 99 {
return false;
}
// 198.18.0.0/15 benchmarking.
if o[0] == 198 && (o[1] == 18 || o[1] == 19) {
return false;
}
// 240.0.0.0/4 reserved (255.255.255.255 is already the broadcast test).
if o[0] >= 240 {
return false;
}
true
}
fn is_public_v6(ip: Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() {
return false;
}
let segments = ip.segments();
// fc00::/7 unique local.
if (segments[0] & 0xfe00) == 0xfc00 {
return false;
}
// fe80::/10 link-local.
if (segments[0] & 0xffc0) == 0xfe80 {
return false;
}
// 2001:db8::/32 documentation.
if segments[0] == 0x2001 && segments[1] == 0x0db8 {
return false;
}
// IPv4-mapped ::ffff:0:0/96 — judge the embedded v4.
let o = ip.octets();
if o[..10].iter().all(|byte| *byte == 0) && o[10] == 0xff && o[11] == 0xff {
return is_public_v4(Ipv4Addr::new(o[12], o[13], o[14], o[15]));
}
true
}
/// Refuse anything that is not one of the four raster formats we render.
///
/// Deliberately by magic bytes, not `Content-Type`: a label is a hint the server
/// chooses, and an SVG (which GdkPixbuf can rasterise at unbounded size) must be
/// rejected *before* it reaches the decoder.
fn sniff_raster(bytes: &[u8]) -> Result<()> {
let raster = bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a])
|| bytes.starts_with(&[0xff, 0xd8, 0xff])
|| bytes.starts_with(b"GIF87a")
|| bytes.starts_with(b"GIF89a")
|| (bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP"));
if raster {
Ok(())
} else {
Err("the icon is not a PNG, JPEG, GIF or WebP image".to_string())
}
}
/// Decode a `data:…` URL body (the part after `data:`).
fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
let (meta, payload) = rest
.split_once(',')
.ok_or("the data URL is malformed")?;
if !meta.starts_with("image/") {
return Err("the data URL is not an image".to_string());
}
if !meta.contains(";base64") {
return Err("only base64 data URLs are supported".to_string());
}
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD
.decode(payload)
.map_err(|_| "the data URL is not valid base64".to_string())?;
if bytes.len() > MAX_BYTES {
return Err("the icon is larger than 1 MiB".to_string());
}
sniff_raster(&bytes)?;
Ok(bytes)
}
/// Turn icon bytes into a `GdkTexture`.
///
/// Must run on the main thread (`gdk::Texture` is not `Send`); the caller does
/// this in a `runtime::spawn` `then`, or while painting a cached icon.
pub fn decode(bytes: &[u8]) -> Result<gdk::Texture> {
let bytes = glib::Bytes::from(bytes);
let texture = gdk::Texture::from_bytes(&bytes)
.map_err(|error| format!("could not decode the icon: {error}"))?;
if texture.width() > MAX_DIMENSION || texture.height() > MAX_DIMENSION {
return Err(format!(
"the icon is {}×{}, too large to render",
texture.width(),
texture.height()
));
}
Ok(texture)
}
/// The on-disk icon cache and the decoded textures for the session.
///
/// Main-thread only (`Rc`/`RefCell`, and `gdk::Texture` is not `Send`). Holds a
/// small in-memory memo of each app's sidecar URL so the per-ping checks do no
/// disk I/O.
#[derive(Default)]
pub struct IconStore {
dir: PathBuf,
/// pubkey → sidecar URL (`None` = no sidecar on disk). Absent = not loaded.
urls: RefCell<HashMap<String, Option<String>>>,
textures: RefCell<HashMap<String, gdk::Texture>>,
in_flight: RefCell<HashSet<(String, String)>>,
/// `(key, url)` pairs whose cache has already been looked at once.
hydrated: RefCell<HashSet<(String, String)>>,
}
impl IconStore {
pub fn new() -> Self {
Self::at(glib::user_cache_dir().join(APP_ID).join("icons"))
}
/// An icon store rooted at an explicit directory. Used by tests.
pub fn at(dir: PathBuf) -> Self {
Self {
dir,
urls: RefCell::new(HashMap::new()),
textures: RefCell::new(HashMap::new()),
in_flight: RefCell::new(HashSet::new()),
hydrated: RefCell::new(HashSet::new()),
}
}
/// A public key is a filename here, so only a clean 64-char hex key passes.
/// `apps.json` is on disk and could be hand-edited; a path must never come
/// out of it.
fn valid_key(key: &str) -> Option<String> {
let key = key.trim();
if key.len() == 64 && key.bytes().all(|byte| byte.is_ascii_hexdigit()) {
Some(key.to_ascii_lowercase())
} else {
None
}
}
fn img_path(&self, key: &str) -> PathBuf {
self.dir.join(format!("{key}.img"))
}
fn url_path(&self, key: &str) -> PathBuf {
self.dir.join(format!("{key}.url"))
}
/// The sidecar URL for `key`, loaded from disk once and memoised.
fn url_for(&self, key: &str) -> Option<String> {
if let Some(known) = self.urls.borrow().get(key) {
return known.clone();
}
let loaded = std::fs::read_to_string(self.url_path(key))
.ok()
.map(|url| url.trim().to_string())
.filter(|url| !url.is_empty());
self.urls
.borrow_mut()
.insert(key.to_string(), loaded.clone());
loaded
}
/// Whether this app's icon still has to be fetched for `url`.
///
/// Armed by the URL alone: a previous failure wrote the same `url` to the
/// sidecar, so a bad URL is retried only when the application changes it —
/// never on the next change ping.
pub fn needs_fetch(&self, key: &str, url: &str) -> bool {
let Some(key) = Self::valid_key(key) else {
return false;
};
self.url_for(&key).as_deref() != Some(url)
}
/// The cached bytes for `url`, only when they were fetched for *that* URL.
pub fn cached_bytes(&self, key: &str, url: &str) -> Option<Vec<u8>> {
let key = Self::valid_key(key)?;
if self.url_for(&key).as_deref() != Some(url) {
return None;
}
std::fs::read(self.img_path(&key)).ok()
}
pub fn texture(&self, key: &str) -> Option<gdk::Texture> {
let key = Self::valid_key(key)?;
self.textures.borrow().get(&key).cloned()
}
pub fn set_texture(&self, key: &str, texture: gdk::Texture) {
if let Some(key) = Self::valid_key(key) {
self.textures.borrow_mut().insert(key, texture);
}
}
/// Drop the decoded textures (not the files). Used when icon loading is turned
/// off, so the rows fall back to initials without losing the cache.
pub fn clear_textures(&self) {
self.textures.borrow_mut().clear();
}
/// Claim `(key, url)` for a fetch. `false` when it is already in flight, was
/// already attempted, or the key is unusable.
pub fn begin(&self, key: &str, url: &str) -> bool {
let Some(key) = Self::valid_key(key) else {
return false;
};
if !self.needs_fetch(&key, url) {
return false;
}
self.in_flight
.borrow_mut()
.insert((key, url.to_string()))
}
/// Claim a one-shot cache hydration for `(key, url)`. `false` when it was
/// already looked at (so a missing cached icon is not probed every ping).
pub fn begin_hydrate(&self, key: &str, url: &str) -> bool {
let Some(key) = Self::valid_key(key) else {
return false;
};
self.hydrated.borrow_mut().insert((key, url.to_string()))
}
/// Release a claim taken by [`IconStore::begin`].
pub fn end(&self, key: &str, url: &str) {
if let Some(key) = Self::valid_key(key) {
self.in_flight.borrow_mut().remove(&(key, url.to_string()));
}
}
/// Persist a successful fetch: `.img` first, then `.url`, so an interrupted
/// write leaves an orphan `.img` that is never served.
pub fn store(&self, key: &str, url: &str, bytes: &[u8]) {
let Some(key) = Self::valid_key(key) else {
return;
};
let _ = std::fs::create_dir_all(&self.dir);
if write_private(&self.img_path(&key), bytes).is_err() {
return;
}
let _ = write_private(&self.url_path(&key), url.as_bytes());
self.urls.borrow_mut().insert(key, Some(url.to_string()));
}
/// Record a failed attempt: remember the URL, drop any stale bytes, and leave
/// the initials in place. The `.url` sidecar is what stops a retry loop.
pub fn mark_failed(&self, key: &str, url: &str) {
let Some(key) = Self::valid_key(key) else {
return;
};
let _ = std::fs::create_dir_all(&self.dir);
let _ = std::fs::remove_file(self.img_path(&key));
let _ = write_private(&self.url_path(&key), url.as_bytes());
self.textures.borrow_mut().remove(&key);
self.urls.borrow_mut().insert(key, Some(url.to_string()));
}
/// Drop an app's cached icon and texture (revoke / logout).
pub fn forget(&self, key: &str) {
let Some(key) = Self::valid_key(key) else {
return;
};
let _ = std::fs::remove_file(self.img_path(&key));
let _ = std::fs::remove_file(self.url_path(&key));
self.urls.borrow_mut().remove(&key);
self.textures.borrow_mut().remove(&key);
}
/// Delete cached icons for keys that are no longer in `live` (every pubkey in
/// the registry, across identities).
pub fn gc(&self, live: &[String]) {
let live: HashSet<String> = live.iter().filter_map(|key| Self::valid_key(key)).collect();
let Ok(entries) = std::fs::read_dir(&self.dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let extension = path.extension().and_then(|value| value.to_str());
if !matches!(extension, Some("img" | "url")) {
continue;
}
let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else {
continue;
};
let Some(stem) = Self::valid_key(stem) else {
continue;
};
if !live.contains(&stem) {
let _ = std::fs::remove_file(&path);
self.urls.borrow_mut().remove(&stem);
self.textures.borrow_mut().remove(&stem);
}
}
}
}
/// Write `bytes` to `path`, creating it mode 0600 on Unix.
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
fn temp_dir() -> PathBuf {
static NEXT: AtomicU32 = AtomicU32::new(0);
let dir = std::env::temp_dir().join(format!(
"regent-icons-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn key() -> String {
// A real-looking client key, but any 64 hex chars work for the store.
"a".repeat(64)
}
#[test]
fn only_https_and_inline_images_are_fetchable() {
assert!(is_fetchable("https://example.com/i.png"));
assert!(is_fetchable("data:image/png;base64,AAAA"));
assert!(!is_fetchable("http://example.com/i.png"));
assert!(!is_fetchable("file:///etc/passwd"));
assert!(!is_fetchable("gopher://example.com"));
assert!(!is_fetchable("data:text/html;base64,AAAA"));
assert!(!is_fetchable("not a url"));
}
fn parse_ip(text: &str) -> IpAddr {
text.parse().unwrap()
}
#[test]
fn private_and_special_addresses_are_not_public() {
for text in [
"127.0.0.1",
"10.0.0.1",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"100.64.0.1",
"0.0.0.0",
"224.0.0.1",
"255.255.255.255",
"192.0.2.1",
"198.18.0.1",
"::1",
"fc00::1",
"fe80::1",
"::ffff:127.0.0.1",
] {
assert!(!is_public(parse_ip(text)), "{text} must not be public");
}
}
#[test]
fn global_addresses_are_public() {
for text in ["1.1.1.1", "8.8.8.8", "2606:4700::1", "::ffff:8.8.8.8"] {
assert!(is_public(parse_ip(text)), "{text} must be public");
}
}
#[test]
fn only_raster_magic_bytes_pass() {
assert!(sniff_raster(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]).is_ok());
assert!(sniff_raster(&[0xff, 0xd8, 0xff, 0xe0]).is_ok());
assert!(sniff_raster(b"GIF89a....").is_ok());
assert!(sniff_raster(b"RIFF\x00\x00\x00\x00WEBPVP8 ").is_ok());
assert!(sniff_raster(b"<svg xmlns=\"...\">").is_err());
assert!(sniff_raster(b"<?xml version=\"1.0\"?>").is_err());
assert!(sniff_raster(b"").is_err());
assert!(sniff_raster(b"RIFF\x00\x00\x00\x00WAVE").is_err());
}
#[test]
fn data_urls_are_checked() {
assert!(decode_data_url("image/png;base64,AAAA").is_err(), "AAAA is not raster");
assert!(decode_data_url("text/plain;base64,AAAA").is_err());
assert!(decode_data_url("image/png,notbase64").is_err());
assert!(decode_data_url("image/png;base64").is_err(), "no comma");
}
#[test]
fn a_failed_url_is_not_retried_until_it_changes() {
let store = IconStore::at(temp_dir());
let key = key();
let url = "https://example.com/i.png";
assert!(store.needs_fetch(&key, url));
assert!(store.begin(&key, url), "first attempt is claimed");
store.end(&key, url);
store.mark_failed(&key, url);
assert!(
!store.needs_fetch(&key, url),
"the same URL must not be retried"
);
assert!(!store.begin(&key, url), "a retry must not be claimable");
assert!(store.needs_fetch(&key, "https://example.com/other.png"));
}
#[test]
fn a_stored_icon_round_trips_and_is_private() {
let dir = temp_dir();
let store = IconStore::at(dir.clone());
let key = key();
let url = "https://example.com/i.png";
let bytes = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
store.store(&key, url, &bytes);
assert!(!store.needs_fetch(&key, url));
assert_eq!(store.cached_bytes(&key, url).as_deref(), Some(&bytes[..]));
assert!(
store.cached_bytes(&key, "https://example.com/other.png").is_none(),
"a different URL must not serve these bytes"
);
// A fresh store reads the sidecar from disk.
let reloaded = IconStore::at(dir.clone());
assert!(!reloaded.needs_fetch(&key, url));
assert_eq!(reloaded.cached_bytes(&key, url).as_deref(), Some(&bytes[..]));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(dir.join(format!("{key}.img")))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
store.forget(&key);
assert!(store.needs_fetch(&key, url));
assert!(!dir.join(format!("{key}.img")).exists());
assert!(!dir.join(format!("{key}.url")).exists());
}
#[test]
fn an_orphan_image_is_never_served() {
let dir = temp_dir();
std::fs::create_dir_all(&dir).unwrap();
let key = key();
let url = "https://example.com/i.png";
// Externally created: the bytes exist, the sidecar does not.
std::fs::write(dir.join(format!("{key}.img")), [0u8; 8]).unwrap();
let store = IconStore::at(dir);
assert!(store.cached_bytes(&key, url).is_none());
assert!(store.needs_fetch(&key, url));
}
#[test]
fn gc_evicts_only_unknown_keys() {
let dir = temp_dir();
let store = IconStore::at(dir.clone());
let live = key();
let dead = "b".repeat(64);
let url = "https://example.com/i.png";
std::fs::create_dir_all(&dir).unwrap();
store.store(&live, url, b"x");
store.store(&dead, url, b"x");
store.gc(&[live.clone()]);
assert!(
dir.join(format!("{live}.img")).exists(),
"the live key is kept"
);
assert!(
!dir.join(format!("{dead}.img")).exists(),
"the dead image is gone"
);
assert!(
!dir.join(format!("{dead}.url")).exists(),
"the dead sidecar is gone"
);
assert!(store.needs_fetch(&dead, url), "the evicted key must refetch");
}
#[test]
fn an_invalid_key_is_refused() {
let dir = temp_dir();
let store = IconStore::at(dir.clone());
store.store("../escape", "https://x/i.png", b"x");
store.mark_failed("short", "https://x/i.png");
assert!(!store.needs_fetch("short", "https://x/i.png"));
assert!(!dir.exists(), "no directory is created for an invalid key");
}
}
+1
View File
@@ -3,5 +3,6 @@
pub mod apps;
pub mod audit;
pub mod icons;
pub mod keys;
pub mod profiles;
+34 -4
View File
@@ -13,6 +13,7 @@ use nostr::nips::nip19::ToBech32;
use zeroize::Zeroizing;
use adw::prelude::*;
use gtk::gdk;
use gtk::gio;
use gtk::gio::prelude::ApplicationExt;
use gtk::prelude::*;
@@ -56,7 +57,15 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
continue;
}
let notified = notify_pending(&widget, notification_body(&question.request));
let decision = present_question(&widget, &question, Some(deadline)).await;
// The icon is shown only when it is already cached: a first
// pairing shows initials, because fetching an unknown app's
// URL before the user says yes is a tracking ping at the
// moment trust is being decided.
let icon = state
.icons()
.texture(&question.client.public_key.to_hex());
let decision =
present_question(&widget, &question, Some(deadline), icon.as_ref()).await;
if notified {
withdraw_pending(&widget);
}
@@ -239,6 +248,7 @@ pub async fn present_question(
widget: &impl IsA<gtk::Widget>,
question: &Question,
deadline: Option<Instant>,
icon: Option<&gdk::Texture>,
) -> Decision {
let request = &question.request;
let choices = match request {
@@ -250,7 +260,7 @@ pub async fn present_question(
let dialog = adw::AlertDialog::builder()
.heading(heading(request))
.body(story(request))
.extra_child(&details(question, widget, deadline))
.extra_child(&details(question, widget, deadline, icon))
.build();
// Heading and body are plain text too: the heading carries no client data
// today, but the extra child is where all of it belongs.
@@ -438,6 +448,7 @@ fn details(
question: &Question,
widget: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
icon: Option<&gdk::Texture>,
) -> gtk::Box {
let client = &question.client;
let content = gtk::Box::builder()
@@ -446,9 +457,9 @@ fn details(
.build();
content.append(&identity_field(&question.identity));
content.append(&plain::text_field(
"Application",
content.append(&application_field(
client.name.as_deref().unwrap_or("(unnamed)"),
icon,
));
// The kind is part of what is being signed, so it sits with the payload
// rather than collapsed under Details.
@@ -566,6 +577,25 @@ fn identity_field(identity: &crate::signer::approval::SigningKey) -> gtk::Box {
plain::field("Signing as", &value)
}
/// The application's name, with its icon when one is cached. The avatar draws
/// initials otherwise — an icon is decoration, never the identifier, and a client
/// must not be able to forge something that looks like Regent's own UI.
fn application_field(name: &str, icon: Option<&gdk::Texture>) -> gtk::Box {
let row = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(10)
.build();
let avatar = adw::Avatar::new(32, Some(name), true);
if let Some(texture) = icon {
avatar.set_custom_image(Some(texture));
}
let label = plain::label(name);
label.set_hexpand(true);
row.append(&avatar);
row.append(&label);
plain::field("Application", &row)
}
/// A titled block for text that may be long, laid out like a quote.
///
/// Bounded: a 5 kB note would otherwise grow the dialog until its buttons left
+46 -1
View File
@@ -15,9 +15,11 @@ use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::runner::{SignerRunner, Status};
use crate::state::AppState;
use crate::store::apps::{App, Permission, Policy};
use crate::store::icons;
use crate::ui::{kind, plain};
/// What the page currently shows, so a log-only change does not rebuild it and
@@ -26,7 +28,7 @@ use crate::ui::{kind, plain};
type Shown = (
Option<String>,
Option<String>,
Vec<(String, Option<String>, Option<String>, Policy)>,
Vec<(String, Option<String>, Option<String>, bool, Policy)>,
);
pub struct AppsView {
@@ -180,6 +182,24 @@ impl Ui {
.cloned()
});
// Icons: show a cached one and start a fetch for the rest. Both calls are
// guarded (memoised URL, in-flight set, one-shot hydration), so this is
// safe on every ping and does no repeated disk work. Runs before the
// signature compare so enabling the preference (or an app changing its
// image) is picked up even when nothing else on the page changed.
if Config::new().load_app_icons() {
for app in &apps {
let Some(url) = app.image.as_deref() else {
continue;
};
if !icons::is_fetchable(url) {
continue;
}
self.state.hydrate_icon(&app.public_key, url);
self.state.load_icon(&app.public_key, url);
}
}
// The shared change channel also fires for activity-log entries. Only
// rebuild when what this page shows changed, or every answered request
// would collapse the expanders.
@@ -192,6 +212,7 @@ impl Ui {
app.public_key.clone(),
app.name.clone(),
app.url.clone(),
self.state.icons().texture(&app.public_key).is_some(),
app.policy.clone(),
)
})
@@ -228,6 +249,11 @@ impl Ui {
}
self.body.append(&group);
self.body.append(&self.forget_all_group());
// Reap icons for apps that are gone (revoke, logout, last key removed).
// Only here, on an actual rebuild — never on every change ping.
let live = self.state.registry().lock().unwrap().client_keys();
self.state.icons().gc(&live);
}
fn app_row(self: &Rc<Self>, app: &App) -> adw::ExpanderRow {
@@ -248,6 +274,13 @@ impl Ui {
};
let row = plain::expander(&name, &byline);
row.set_subtitle_lines(1);
// The icon is decoration: the plain-text name above stays the identifier,
// and an application without a (fetchable) icon keeps its initials.
let avatar = adw::Avatar::new(32, Some(&name), true);
if let Some(texture) = self.state.icons().texture(&app.public_key) {
avatar.set_custom_image(Some(&texture));
}
row.add_prefix(&avatar);
// When the byline is a shortened npub, keep the full key in a tooltip.
if app.url.is_none() {
row.set_tooltip_text(Some(&npub));
@@ -314,11 +347,13 @@ impl Ui {
.css_classes(["destructive-action"])
.build();
let ui = Rc::clone(self);
let key = app.public_key.clone();
revoke.connect_clicked(move |_| {
let registry = ui.state.registry();
if let Err(error) = registry.lock().unwrap().revoke(&public_key) {
eprintln!("regent: could not revoke an application: {error}");
}
ui.state.icons().forget(&key);
ui.state.notify_changes();
});
row.add_suffix(&revoke);
@@ -376,9 +411,19 @@ impl Ui {
return;
};
let registry = ui.state.registry();
let keys: Vec<String> = registry
.lock()
.unwrap()
.list_for(identity)
.iter()
.map(|app| app.public_key.clone())
.collect();
if let Err(error) = registry.lock().unwrap().clear_for(identity) {
eprintln!("regent: could not forget applications: {error}");
}
for key in &keys {
ui.state.icons().forget(key);
}
ui.state.notify_changes();
});
row.add_suffix(&forget);
+4 -2
View File
@@ -395,8 +395,10 @@ impl ConnectDialog {
glib::MainContext::default().spawn_local(async move {
// The same approval dialog as a responder question: the app is
// registered *before* the response goes out, and the user is the
// one who decides.
let decision = approval::present_question(&parent, &question, None).await;
// one who decides. A re-pairing may already have a cached icon; a
// first pairing shows initials (no fetch before consent).
let icon = connect.state.icons().texture(&pairing.client.to_hex());
let decision = approval::present_question(&parent, &question, None, icon.as_ref()).await;
if decision == Decision::Deny {
return;
}
+35
View File
@@ -164,10 +164,29 @@ impl Preferences {
auto_approve.set_subtitle("Requests per minute, per application. Zero never answers silently.");
behaviour.add(&auto_approve);
// --- App icons. ---
let appearance = adw::PreferencesGroup::builder()
.title("Appearance")
.description(
"Applications may declare an icon. Regent fetches it from the \
application's own server, after you approve it.",
)
.build();
// Markup off before the strings are set: an `AdwPreferencesRow` renders
// its title/subtitle as Pango markup by default.
let load_icons = adw::SwitchRow::builder()
.use_markup(false)
.active(Config::new().load_app_icons())
.build();
load_icons.set_title("Load app icons");
load_icons.set_subtitle("Fetch and show the icons applications declare when pairing");
appearance.add(&load_icons);
let page = adw::PreferencesPage::new();
page.add(&signer_group);
page.add(&vault);
page.add(&behaviour);
page.add(&appearance);
let dialog = adw::PreferencesDialog::new();
dialog.set_title("Preferences");
@@ -254,6 +273,22 @@ impl Preferences {
}
});
}
{
let preferences = Rc::clone(&preferences);
load_icons.connect_active_notify(move |row| {
let load = row.is_active();
let config = Config::new();
if config.load_app_icons() != load {
config.set_load_app_icons(load);
}
if !load {
// Drop the decoded textures and rebuild, so the rows fall
// back to initials without touching the cache on disk.
preferences.state.icons().clear_textures();
}
preferences.state.notify_changes();
});
}
{
let preferences = Rc::clone(&preferences);
let state = preferences.state.clone();