Add M8: a NIP-49 key vault with a global passphrase

This commit is contained in:
raucao committed 2026-11-23 23:43:14 +04:00
1 parent 01178ac10c
commit 623ef35bac
20 files changed
+1878 -872

No files matched your search

Generated
+3 -440
View File
@@ -29,38 +29,12 @@ dependencies = [
"cpufeatures 0.2.17",
]
[[package]]
name = "aes"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
dependencies = [
"cipher 0.5.2",
"cpubits",
"cpufeatures 0.3.1",
"zeroize",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "ashpd"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc"
dependencies = [
"bitflags 2.13.2",
"futures-util",
"getrandom 0.4.3",
"serde",
"tokio",
"zbus",
]
[[package]]
name = "async-channel"
version = "2.5.0"
@@ -73,17 +47,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "async-trait"
version = "0.1.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "async-utility"
version = "0.3.2"
@@ -227,7 +190,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
@@ -239,15 +201,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
dependencies = [
"hybrid-array",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -310,15 +263,6 @@ dependencies = [
"cipher 0.4.4",
]
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher 0.5.2",
]
[[package]]
name = "cc"
version = "1.11.1"
@@ -389,7 +333,6 @@ dependencies = [
"block-buffer 0.12.1",
"crypto-common 0.2.2",
"inout 0.2.6",
"zeroize",
]
[[package]]
@@ -407,18 +350,6 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -543,7 +474,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer 0.12.1",
"const-oid",
"crypto-common 0.2.2",
"ctutils",
]
@@ -565,12 +495,6 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "endi"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -619,12 +543,6 @@ dependencies = [
"serde",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -1091,12 +1009,6 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.3"
@@ -1115,15 +1027,6 @@ dependencies = [
"arrayvec",
]
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
@@ -1156,7 +1059,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
"zeroize",
]
[[package]]
@@ -1292,7 +1194,7 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"block-padding 0.3.3",
"block-padding",
"generic-array",
]
@@ -1302,7 +1204,6 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"block-padding 0.4.2",
"hybrid-array",
]
@@ -1359,18 +1260,6 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
@@ -1389,16 +1278,6 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
[[package]]
name = "md-5"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest 0.11.3",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -1467,12 +1346,12 @@ version = "0.45.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7a55567533eb00df5a6e2855f229e2092f593ab67c97aff7521fdfe55cf0383"
dependencies = [
"aes 0.8.4",
"aes",
"base64",
"bech32",
"bip39",
"bitcoin_hashes 1.2.0",
"cbc 0.1.2",
"cbc",
"chacha20",
"chacha20poly1305",
"faster-hex",
@@ -1531,86 +1410,6 @@ dependencies = [
"universal-time",
]
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-bigint-dig"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7f9a86e097b0d187ad0e65667c2f58b9254671e86e7dbb78036b16692eae099"
dependencies = [
"libm",
"num-integer",
"num-iter",
"num-traits",
"once_cell",
"rand 0.9.5",
"serde",
"smallvec",
"zeroize",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1626,34 +1425,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oo7"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9484776a7b58eadca65c2e247499d2fd926a914f65633d68c5d17c157db8479"
dependencies = [
"aes 0.9.4",
"ashpd",
"cbc 0.2.1",
"endi",
"futures-util",
"getrandom 0.4.3",
"hex",
"hkdf",
"md-5",
"num",
"num-bigint-dig",
"pbkdf2",
"serde",
"serde_bytes",
"sha2",
"subtle",
"tokio",
"zbus",
"zeroize",
"zgvariant",
]
[[package]]
name = "opaque-debug"
version = "0.3.1"
@@ -1666,16 +1437,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f933a4265d5cdad61d19bbdfc972ea5726d56cd8d3d57b8f2d3c365dd42bee9"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "pango"
version = "0.22.9"
@@ -1915,7 +1676,6 @@ dependencies = [
"libadwaita",
"nostr",
"nostr-sdk",
"oo7",
"qrcode",
"serde",
"serde_json",
@@ -1947,19 +1707,6 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -2058,16 +1805,6 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde_bytes"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
dependencies = [
"serde",
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
@@ -2101,17 +1838,6 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_repr"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
@@ -2264,19 +1990,6 @@ version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -2346,7 +2059,6 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -2491,21 +2203,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -2540,17 +2240,6 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -2622,17 +2311,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "uuid"
version = "1.29.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c"
dependencies = [
"js-sys",
"serde_core",
"wasm-bindgen",
]
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -2875,69 +2553,6 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zbus"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"socket2",
"tokio",
"tracing",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus_macros"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_utils",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow",
]
[[package]]
name = "zcheapstr"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
dependencies = [
"serde",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
@@ -2984,20 +2599,6 @@ name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerotrie"
@@ -3032,33 +2633,6 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "zgvariant"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5576e785f58266b3c26ef3b35d5914991981226733376d8ce34d185c0fccb240"
dependencies = [
"endi",
"serde",
"serde_bytes",
"winnow",
"zbus_utils",
"zcheapstr",
"zgvariant_derive",
]
[[package]]
name = "zgvariant_derive"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd6ca94bb7097734710aa30f08cc9979045b220e743ca3a5d6cda1bed58396e9"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_utils",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -3070,14 +2644,3 @@ name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zruntime"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72"
dependencies = [
"futures-core",
"futures-io",
"tracing",
]
-1
View File
@@ -16,7 +16,6 @@ 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"] }
oo7 = { version = "0.7", features = ["tokio"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal"] }
async-channel = "2"
serde_json = "1"
+48 -24
View File
@@ -2,28 +2,28 @@
# End-to-end acceptance for Regent.
#
# Covers three levels:
# 1. the keyring round-trip test
# 2. the `nak` loopback test (an independent NIP-46 client against our responder)
# 3. the app itself: a seeded identity key makes the signer come up and listen
# 1. the `nak` loopback test (an independent NIP-46 client against our responder)
# 2. the vault itself (NIP-49 keys, mode 0600, no plaintext identity key)
# 3. the app: a seeded identity key makes the signer come up and listen
#
# Needs a D-Bus session and a keyring daemon, so wrap it:
# The GUI needs a D-Bus session, so wrap it:
#
# dbus-run-session -- build-aux/acceptance.sh
#
# On a normal desktop session you can simply run it directly — gnome-keyring is
# already there. Everything happens in a throwaway HOME.
# Headless mode no longer needs a session bus or a keyring daemon. Everything
# happens in a throwaway HOME.
set -u
ROOT=$(cd "$(dirname "$0")/.." && pwd)
BUILD=${REGENT_BUILD_DIR:-_build}
PORT=${REGENT_TEST_PORT:-10577}
DATA_DIR=org.kosmos.raucao.Regent
ORIGINAL_HOME=$HOME
TMP_HOME=$(mktemp -d)
export HOME=$TMP_HOME
# Keep cargo's registry cache; a fresh CARGO_HOME would re-download everything.
export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
mkdir -p "$HOME/.local/share/keyrings"
cleanup() {
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} 2>/dev/null
@@ -42,7 +42,7 @@ check() {
fi
}
for tool in cargo nak secret-tool gnome-keyring-daemon gtk4-broadwayd; do
for tool in cargo nak gtk4-broadwayd; do
command -v "$tool" >/dev/null || {
printf 'missing: %s\n' "$tool" >&2
exit 2
@@ -51,21 +51,44 @@ done
cd "$ROOT" || exit 2
printf '== keyring and responder tests ==\n'
eval "$(printf test | gnome-keyring-daemon --unlock --components=secrets 2>/dev/null)"
sleep 1
printf '== responder tests ==\n'
CARGO_TARGET_DIR="$BUILD/cargo-target" cargo test --release -- --ignored >"$TMP_HOME/tests.log" 2>&1
grep -q 'test result: ok' "$TMP_HOME/tests.log"
check $? "cargo tests (keyring round-trip, nak loopback)"
check $? "cargo tests (nak loopback)"
tail -4 "$TMP_HOME/tests.log" | sed 's/^/ /'
printf '\n== the app, end to end ==\n'
printf '\n== the key vault ==\n'
SECRET=$(nak key generate)
printf '%s' "$SECRET" | secret-tool store --label="Regent identity key" \
application org.kosmos.raucao.Regent kind user
[ "$(secret-tool lookup application org.kosmos.raucao.Regent kind user)" = "$SECRET" ]
check $? "identity key seeded in the keyring"
PUBKEY=$(nak key public "$SECRET")
PASSPHRASE=acceptance-passphrase
NCRYPTSEC=$(nak key encrypt "$SECRET" "$PASSPHRASE")
VAULT="$HOME/.local/share/$DATA_DIR/keys.json"
mkdir -p "$(dirname "$VAULT")"
cat >"$VAULT" <<EOF
{
"version": 1,
"keys": [
{ "pubkey": "$PUBKEY", "name": "Acceptance", "ncryptsec": "$NCRYPTSEC" }
]
}
EOF
chmod 600 "$VAULT"
grep -q 'ncryptsec1' "$VAULT"
check $? "the seeded identity key is NIP-49 encrypted"
! grep -q "$SECRET" "$VAULT"
check $? "no plaintext identity key is on disk"
[ "$(stat -c %a "$VAULT")" = 600 ]
check $? "the vault is mode 0600"
PASSPHRASE_FILE="$TMP_HOME/passphrase"
printf '%s' "$PASSPHRASE" >"$PASSPHRASE_FILE"
chmod 600 "$PASSPHRASE_FILE"
printf '\n== the app, end to end ==\n'
nak serve --port "$PORT" >/dev/null 2>&1 &
RELAY=$!
gtk4-broadwayd :11 >/dev/null 2>&1 &
@@ -83,9 +106,9 @@ sleep 6
grep -q 'signer listening' "$TMP_HOME/app.log"
check $? "the app started the signer ($(grep -m1 'signer listening' "$TMP_HOME/app.log" || echo 'no log line'))"
# The app must have generated and stored a device key of its own.
[ -n "$(secret-tool lookup application org.kosmos.raucao.Regent kind device 2>/dev/null)" ]
check $? "a device key was created in the keyring"
# The app must have generated and stored a device key of its own, in the vault.
grep -q '"device"' "$VAULT"
check $? "a device key was created in the vault"
# The GUI owns the D-Bus name; headless must not run alongside it, and we need
# it gone so the two do not race over apps.json.
@@ -105,7 +128,8 @@ sleep 2
URI="nostrconnect://$CLIENT?relay=ws%3A%2F%2F127.0.0.1%3A$PORT&secret=acceptance&name=Acceptance%20Client&perms=sign_event%3A1"
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --pair "$URI" >"$TMP_HOME/headless.log" 2>&1 &
"$ROOT/$BUILD/regent" --pair "$URI" --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/headless.log" 2>&1 &
HEADLESS=$!
sleep 5
@@ -115,12 +139,12 @@ check $? "headless signer started with no window"
grep -q 'paired with Acceptance Client' "$TMP_HOME/headless.log"
check $? "CLI paired from a nostrconnect:// URI"
grep -q '"name": "Acceptance Client"' "$HOME/.config/org.kosmos.raucao.Regent/apps.json"
grep -q '"name": "Acceptance Client"' "$HOME/.config/$DATA_DIR/apps.json"
check $? "the paired application was recorded"
# Pairing must never auto-grant: the stored policy stays empty.
grep -q '"methods": \[\]' "$HOME/.config/org.kosmos.raucao.Regent/apps.json" &&
grep -q '"kinds": \[\]' "$HOME/.config/org.kosmos.raucao.Regent/apps.json"
grep -q '"methods": \[\]' "$HOME/.config/$DATA_DIR/apps.json" &&
grep -q '"kinds": \[\]' "$HOME/.config/$DATA_DIR/apps.json"
check $? "the pairing auto-granted nothing"
grep -q "$CLIENT" "$TMP_HOME/subscriber.log"
@@ -21,6 +21,11 @@
<summary>Auto-approval rate limit</summary>
<description>How many requests per minute a stored "allow always" permission may answer without asking, per application. Once an application exceeds it Regent asks again, so a runaway client turns back into prompts instead of an unbounded silent stream. Zero means never answer silently.</description>
</key>
<key name="lock-timeout" type="i">
<default>900</default>
<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="relays" type="as">
<default>['wss://nostr.kosmos.org']</default>
<summary>Relays</summary>
+33
View File
@@ -7,6 +7,7 @@ use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::ui::approval;
use crate::window::Window;
use crate::{APP_ID, RESOURCE_PATH};
@@ -25,6 +26,38 @@ pub fn run() -> glib::ExitCode {
// same registry and signer.
let state = AppState::new();
// Lock or unlock the key vault. Unlocking asks for the passphrase on the
// active window; a locked vault fails closed, so this never signs anything.
let lock = gio::SimpleAction::new("lock", None);
{
let app = app.clone();
let state = Rc::clone(&state);
lock.connect_activate(move |_, _| {
let Some(store) = state.store() else {
return;
};
if !store.is_locked() {
store.lock();
eprintln!("regent: the key vault is locked");
state.notify();
return;
}
let widget = app.active_window().map(|window| window.upcast::<gtk::Widget>());
let state = Rc::clone(&state);
glib::MainContext::default().spawn_local(async move {
let unlocked = match &widget {
Some(widget) => approval::present_unlock(widget, store).await,
None => false,
};
if unlocked {
state.notify();
}
});
});
}
app.add_action(&lock);
app.set_accels_for_action("app.lock", &["<primary>l"]);
app.connect_startup(|_| load_css());
app.connect_activate(move |app| Window::new(app, Rc::clone(&state)).present());
+16
View File
@@ -50,6 +50,22 @@ impl Config {
self.settings.int("auto-approve-limit").max(0) as u32
}
/// How long the key vault stays open after it is unlocked, in seconds.
/// Zero means never lock automatically.
///
/// This is a hard timeout since the unlock, deliberately **not** an idle
/// timer that request traffic resets: otherwise a chatty client would hold
/// the vault open forever.
pub fn lock_timeout(&self) -> u32 {
self.settings.int("lock-timeout").max(0) as u32
}
pub fn set_lock_timeout(&self, seconds: u32) {
if let Err(error) = self.settings.set_int("lock-timeout", seconds as i32) {
eprintln!("regent: could not save the auto-lock timeout: {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> {
+153 -23
View File
@@ -5,19 +5,25 @@
//! approval bridge's questions are answered `Deny` immediately rather than
//! waiting out the timeout. Pre-approve in the GUI, then run headless.
//!
//! The same applies to the key vault: with no window there is nobody to type the
//! passphrase, so a locked vault denies the sensitive methods unless
//! `--passphrase-file` (or a systemd credential) opened it at startup.
//!
//! Deliberately not a `GtkApplication`: headless must work with no display, and
//! nothing here needs GTK. It is a plain tokio program.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use glib::prelude::ToVariant;
use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
use zeroize::Zeroizing;
use crate::config::Config;
use crate::runtime;
use crate::signer::approval::{Approver, Decision};
use crate::signer::approval::{Approver, Decision, Prompt};
use crate::signer::{ClientPairing, Signer, SignerConfig, parse_client_uri};
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
@@ -25,9 +31,14 @@ use crate::store::keys::KeyStore;
use crate::APP_ID;
/// Run headless. `pair` is a `nostrconnect://` URI when `--pair` was given;
/// `key` selects the identity that pairing is bound to.
pub fn run(pair: Option<String>, key: Option<String>) -> glib::ExitCode {
match runtime::block_on(serve(pair.as_deref(), key.as_deref())) {
/// `key` selects the identity that pairing is bound to; `passphrase_file` is
/// where to read the vault passphrase from, if anywhere.
pub fn run(
pair: Option<String>,
key: Option<String>,
passphrase_file: Option<String>,
) -> glib::ExitCode {
match runtime::block_on(serve(pair.as_deref(), key.as_deref(), passphrase_file.as_deref())) {
Ok(()) => glib::ExitCode::SUCCESS,
Err(error) => {
eprintln!("regent: {error}");
@@ -36,32 +47,54 @@ pub fn run(pair: Option<String>, key: Option<String>) -> glib::ExitCode {
}
}
async fn serve(pair: Option<&str>, key: Option<&str>) -> Result<(), String> {
async fn serve(
pair: Option<&str>,
key: Option<&str>,
passphrase_file: Option<&str>,
) -> Result<(), String> {
// Two signers on one device key would both answer and would overwrite each
// other's apps.json. The GUI owns this name; refuse to run alongside it.
// other's apps.json. The GUI owns the app's D-Bus name; refuse to run
// alongside it.
if another_instance_running()? {
return Err("Regent is already running".to_string());
}
// Parse the URI before touching the keyring: a bad argument fails fast.
// Parse the URI before touching the vault: a bad argument fails fast.
let pairing = match pair {
Some(uri) => Some(parse_client_uri(uri).map_err(|error| error.to_string())?),
None => None,
};
// The passphrase is read once, here, and never logged.
let passphrase = read_passphrase(passphrase_file)?;
let store = KeyStore::connect()
.await
.map_err(|error| error.to_string())?;
let stored = store
.list_user_keys()
.await
.map_err(|error| error.to_string())?;
let stored = store.list_user_keys();
if stored.is_empty() {
return Err(
"no identity key is stored; create or import one in the GUI first".to_string(),
);
}
match passphrase {
Some(passphrase) => {
store
.unlock(passphrase.as_str())
.await
.map_err(|error| format!("could not unlock the key vault: {error}"))?;
// The vault holds the keys now; the passphrase is dropped here, at
// the end of the arm, rather than living on for the whole run.
}
None if store.is_locked() => {
eprintln!(
"regent: the key vault is locked, so signing, encryption and decryption will be \
denied; pass --passphrase-file (or a systemd credential) to unlock it"
);
}
None => {}
}
let settings = Config::new();
// `--key` picks the identity for `--pair`; otherwise the UI's selection, then
// the first stored key.
@@ -87,11 +120,19 @@ async fn serve(pair: Option<&str>, key: Option<&str>) -> Result<(), String> {
let names = Arc::new(Mutex::new(names));
let default_identity = Arc::new(Mutex::new(Some(identity)));
// No window: deny everything the user has not already allowed.
let (approver, questions) = Approver::new();
// No window: deny everything the user has not already allowed, and never
// open the vault (an unattended `--passphrase-file` does that at startup).
let (approver, prompts) = Approver::new();
tokio::spawn(async move {
while let Ok(question) = questions.recv().await {
let _ = question.reply.send(Decision::Deny).await;
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Deny).await;
}
Prompt::Unlock { reply } => {
let _ = reply.send(false).await;
}
}
}
});
@@ -178,15 +219,18 @@ async fn finish_pairing(
Ok(())
}
/// True if another Regent (the GUI, or another headless run) owns the app's
/// D-Bus name. The session bus is required for the keyring, so a missing one is
/// an error rather than a silent "not running".
/// True if another Regent is already running.
///
/// The GUI owns the app's D-Bus name, so that is the first check. With no
/// session bus at all (a server, an SSH box) the GUI cannot run either, so an
/// exclusive lock on `regent.lock` catches a second **headless** run — which the
/// D-Bus check alone never could. The kernel releases the lock on exit, so it
/// cannot go stale.
fn another_instance_running() -> Result<bool, String> {
let connection = gtk::gio::bus_get_sync(
gtk::gio::BusType::Session,
gtk::gio::Cancellable::NONE,
)
.map_err(|error| format!("Regent needs a D-Bus session bus: {error}"))?;
let Some(connection) = session_bus() else {
return Ok(!claim_lock_file());
};
let reply = connection
.call_sync(
Some("org.freedesktop.DBus"),
@@ -204,6 +248,92 @@ fn another_instance_running() -> Result<bool, String> {
Ok(owned)
}
fn session_bus() -> Option<gtk::gio::DBusConnection> {
gtk::gio::bus_get_sync(gtk::gio::BusType::Session, gtk::gio::Cancellable::NONE).ok()
}
/// Hold `regent.lock` for the life of the process. False if another process has
/// it. Failing to create the file is not a reason to refuse to run.
fn claim_lock_file() -> bool {
static LOCK: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let Ok(file) = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&path)
else {
return true;
};
match file.try_lock() {
Ok(()) => {
let _ = LOCK.set(file);
true
}
Err(std::fs::TryLockError::WouldBlock) => false,
Err(std::fs::TryLockError::Error(_)) => true,
}
}
/// The passphrase for an unattended run: a systemd credential
/// (`$CREDENTIALS_DIRECTORY/regent-passphrase`) first, then `--passphrase-file`.
/// Never argv or the environment, and never logged.
fn read_passphrase(file: Option<&str>) -> Result<Option<Zeroizing<String>>, String> {
let credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|dir| PathBuf::from(dir).join("regent-passphrase"));
let path = match credential {
Some(path) if path.exists() => Some(path),
_ => file.map(PathBuf::from),
};
let Some(path) = path else {
return Ok(None);
};
let metadata = std::fs::metadata(&path)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
if !metadata.is_file() {
return Err(format!(
"--passphrase-file {}: not a regular file",
path.display()
));
}
if metadata.len() > 4096 {
return Err(format!(
"--passphrase-file {}: too large to be a passphrase",
path.display()
));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
eprintln!(
"regent: warning: {} is readable by other users",
path.display()
);
}
}
let text = std::fs::read_to_string(&path)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
let passphrase = text.trim_end_matches(['\n', '\r']).to_string();
if passphrase.is_empty() {
return Err(format!(
"--passphrase-file {}: the passphrase is empty",
path.display()
));
}
Ok(Some(Zeroizing::new(passphrase)))
}
async fn wait_for_shutdown() {
use tokio::signal::unix::{SignalKind, signal};
+50 -30
View File
@@ -22,7 +22,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
const USAGE: &str = "\
Regent — a Nostr remote signer (NIP-46) for GNOME
Usage: regent [--headless] [--pair <uri>] [--key <npub|hex>]
Usage: regent [--headless] [--pair <uri>] [--key <npub|hex>] [--passphrase-file <path>]
regent --version
regent --help
@@ -33,6 +33,10 @@ Options:
headless
--key <key> identity (npub or hex) that --pair binds the client to; the
current identity is used when omitted
--passphrase-file <path>
read the key-vault passphrase from this file (mode 0400/0600)
so an unattended run can sign; a systemd credential named
regent-passphrase is used instead when present
--version, -V print the version and exit
--help, -h print this help and exit
@@ -51,7 +55,7 @@ fn main() -> glib::ExitCode {
return glib::ExitCode::SUCCESS;
}
let (headless, pair, key) = match parse_args(&args) {
let parsed = match parse_args(&args) {
Ok(parsed) => parsed,
Err(error) => {
eprintln!("regent: {error}");
@@ -60,53 +64,69 @@ fn main() -> glib::ExitCode {
}
};
if headless || pair.is_some() || key.is_some() {
return headless::run(pair, key);
if parsed.headless || parsed.pair.is_some() || parsed.key.is_some() {
return headless::run(parsed.pair, parsed.key, parsed.passphrase_file);
}
register_resources();
application::run()
}
/// Parse the (few) arguments we accept: `--headless`, `--pair <uri>`,
/// `--key <npub|hex>`.
fn parse_args(args: &[String]) -> Result<(bool, Option<String>, Option<String>), String> {
let mut headless = false;
let mut pair = None;
let mut key = None;
/// The (few) arguments we accept.
struct Args {
headless: bool,
pair: Option<String>,
key: Option<String>,
passphrase_file: Option<String>,
}
/// Parse `--headless`, `--pair <uri>`, `--key <npub|hex>` and
/// `--passphrase-file <path>`.
fn parse_args(args: &[String]) -> Result<Args, String> {
let mut parsed = Args {
headless: false,
pair: None,
key: None,
passphrase_file: None,
};
let mut iter = args.iter();
while let Some(arg) = iter.next() {
match arg.as_str() {
"--headless" => headless = true,
"--pair" => {
let value = iter
.next()
.ok_or("--pair needs a nostrconnect:// URI")?
.clone();
if value.starts_with('-') {
return Err("--pair needs a nostrconnect:// URI, not a flag".to_string());
}
pair = Some(value);
}
"--key" => {
let value = iter.next().ok_or("--key needs an npub or hex key")?.clone();
if value.starts_with('-') {
return Err("--key needs an npub or hex key, not a flag".to_string());
}
key = Some(value);
"--headless" => parsed.headless = true,
"--pair" => parsed.pair = Some(value_for(&mut iter, "--pair", "a nostrconnect:// URI")?),
"--key" => parsed.key = Some(value_for(&mut iter, "--key", "an npub or hex key")?),
"--passphrase-file" => {
parsed.passphrase_file =
Some(value_for(&mut iter, "--passphrase-file", "a path")?)
}
_ => {
if let Some(value) = arg.strip_prefix("--pair=") {
pair = Some(value.to_string());
parsed.pair = Some(value.to_string());
} else if let Some(value) = arg.strip_prefix("--key=") {
key = Some(value.to_string());
parsed.key = Some(value.to_string());
} else if let Some(value) = arg.strip_prefix("--passphrase-file=") {
parsed.passphrase_file = Some(value.to_string());
} else {
return Err(format!("unknown argument: {arg}"));
}
}
}
}
Ok((headless, pair, key))
Ok(parsed)
}
/// The value after a flag, rejecting a following flag so `--pair --headless`
/// fails loudly instead of pairing with the literal string `--headless`.
fn value_for(
iter: &mut std::slice::Iter<'_, String>,
flag: &str,
what: &str,
) -> Result<String, String> {
let value = iter.next().ok_or(format!("{flag} needs {what}"))?.clone();
if value.starts_with('-') {
return Err(format!("{flag} needs {what}, not a flag"));
}
Ok(value)
}
/// Directories that may hold an installed copy of the GResource, in the order
+55 -8
View File
@@ -96,21 +96,26 @@ pub struct Question {
pub rebind_from: Option<PublicKey>,
}
/// One question for the user, with the channel to answer on.
pub struct ApprovalRequest {
pub question: Question,
pub reply: Sender<Decision>,
/// One thing the responder needs from the user, with the channel to answer on.
pub enum Prompt {
/// Decide on a request.
Approve {
question: Question,
reply: Sender<Decision>,
},
/// Open the vault. `true` means it is now unlocked.
Unlock { reply: Sender<bool> },
}
/// The handle the responder uses to ask the user.
#[derive(Clone)]
pub struct Approver {
inbox: Sender<ApprovalRequest>,
inbox: Sender<Prompt>,
}
impl Approver {
/// Create an approver and the receiver the UI must drain.
pub fn new() -> (Self, Receiver<ApprovalRequest>) {
pub fn new() -> (Self, Receiver<Prompt>) {
let (inbox, questions) = async_channel::unbounded();
(Self { inbox }, questions)
}
@@ -124,8 +129,12 @@ impl Approver {
/// without waiting a minute.
async fn ask_within(&self, within: Duration, question: Question) -> Decision {
let (reply, answer) = bounded(1);
let pending = ApprovalRequest { question, reply };
if self.inbox.send(pending).await.is_err() {
if self
.inbox
.send(Prompt::Approve { question, reply })
.await
.is_err()
{
return Decision::Deny;
}
match tokio::time::timeout(within, answer.recv()).await {
@@ -133,6 +142,25 @@ impl Approver {
_ => Decision::Deny,
}
}
/// Ask the user to open the vault.
///
/// A timeout, a missing UI or a refusal is `false`: no answer never means
/// "unlocked". A locked vault fails closed exactly like a declined request.
pub async fn ask_unlock(&self) -> bool {
self.ask_unlock_within(ASK_TIMEOUT).await
}
async fn ask_unlock_within(&self, within: Duration) -> bool {
let (reply, answer) = bounded(1);
if self.inbox.send(Prompt::Unlock { reply }).await.is_err() {
return false;
}
match tokio::time::timeout(within, answer.recv()).await {
Ok(Ok(unlocked)) => unlocked,
_ => false,
}
}
}
#[cfg(test)]
@@ -190,4 +218,23 @@ mod tests {
);
drain.abort();
}
/// A UI that never answers must not unlock the vault either.
#[tokio::test]
async fn a_silent_ui_never_unlocks() {
let (approver, questions) = Approver::new();
let holding = tokio::spawn(async move {
while let Ok(prompt) = questions.recv().await {
tokio::time::sleep(Duration::from_secs(30)).await;
drop(prompt);
}
});
assert!(
!approver
.ask_unlock_within(Duration::from_millis(50))
.await,
"no answer is not an unlock"
);
holding.abort();
}
}
+296 -51
View File
@@ -55,12 +55,20 @@ impl IdentityKeys {
.cloned()
.ok_or_else(|| "that identity key is not available".into()),
Self::Store(store) => store
.user_key(public_key)
.await?
.user_key(public_key)?
.ok_or_else(|| "that identity key is no longer stored".into()),
}
}
/// Whether the vault must be opened before a key can be used. In-memory
/// test keys are never locked.
pub fn is_locked(&self) -> bool {
match self {
Self::Store(store) => store.is_locked(),
_ => false,
}
}
/// The fallback identity when none is selected.
pub async fn first(&self) -> Result<PublicKey> {
match self {
@@ -72,7 +80,6 @@ impl IdentityKeys {
.ok_or_else(|| "no identity key is stored".into()),
Self::Store(store) => store
.list_user_keys()
.await?
.first()
.map(|key| key.public_key)
.ok_or_else(|| "no identity key is stored".into()),
@@ -91,7 +98,7 @@ impl IdentityKeys {
}
/// Everything the responder needs, so tests can supply keys directly instead of
/// going through the keyring.
/// going through the vault.
pub struct SignerConfig {
pub device_keys: Keys,
/// Identity keys, resolved per request.
@@ -136,7 +143,7 @@ impl SignerConfig {
default_identity: Arc<Mutex<Option<PublicKey>>>,
) -> Result<Self> {
Ok(Self {
device_keys: store.device_key().await?,
device_keys: store.device_key()?,
keys: IdentityKeys::Store(store),
names,
default_identity,
@@ -761,29 +768,18 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
preview: preview(&incoming.content),
tags: tag_summary(&incoming.tags),
};
let verdict = gate(
let keys = authorize(
config,
&client,
identity,
request,
Some(Permission::Kind(kind)),
)
.await;
record(
config,
&client,
"sign_event",
Some(kind),
Some(&identity),
verdict.outcome(),
);
match verdict {
Verdict::Deny => Err("the user declined to sign the event".to_string()),
_ => match config.keys.get(&identity).await {
Err(error) => Err(error.to_string()),
Ok(keys) => sign(incoming, &keys),
},
}
"the user declined to sign the event",
)
.await;
keys.and_then(|keys| sign(incoming, &keys))
}
},
},
@@ -797,24 +793,18 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
let verdict = gate(
let keys = authorize(
config,
&client,
identity,
request,
Some(Permission::Method(m.to_string())),
m,
None,
"the user declined to encrypt the message",
)
.await;
record(config, &client, m, None, Some(&identity), verdict.outcome());
match verdict {
Verdict::Deny => {
Err("the user declined to encrypt the message".to_string())
}
_ => match config.keys.get(&identity).await {
Err(error) => Err(error.to_string()),
Ok(keys) => encrypt(m, keys.secret_key(), &peer, payload(&params)),
},
}
keys.and_then(|keys| encrypt(m, keys.secret_key(), &peer, payload(&params)))
}
},
},
@@ -830,17 +820,18 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
let verdict = gate(config, &client, identity, request, None).await;
record(config, &client, m, None, Some(&identity), verdict.outcome());
match verdict {
Verdict::Deny => {
Err("the user declined to decrypt the message".to_string())
}
_ => match config.keys.get(&identity).await {
Err(error) => Err(error.to_string()),
Ok(keys) => decrypt(m, keys.secret_key(), &peer, payload(&params)),
},
}
let keys = authorize(
config,
&client,
identity,
request,
None,
m,
None,
"the user declined to decrypt the message",
)
.await;
keys.and_then(|keys| decrypt(m, keys.secret_key(), &peer, payload(&params)))
}
},
},
@@ -930,6 +921,64 @@ async fn gate(
}
}
/// Put a sensitive request through the policy gate and open the vault.
///
/// Records exactly one outcome. The vault is opened **before** the record, so a
/// request the vault refused is logged as `locked` and never as allowed or
/// silent: the activity log must not claim an answer that was never produced.
#[allow(clippy::too_many_arguments)]
async fn authorize(
config: &SignerConfig,
client: &ClientInfo,
identity: PublicKey,
request: Request,
permission: Option<Permission>,
method: &str,
kind: Option<u16>,
declined: &str,
) -> std::result::Result<Keys, String> {
let verdict = gate(config, client, identity, request, permission).await;
if verdict == Verdict::Deny {
record(config, client, method, kind, Some(&identity), verdict.outcome());
return Err(declined.to_string());
}
// The user allowed it, but the key is behind the passphrase. Ask once; a
// timeout, a missing UI or a refusal is a denial, exactly like any other
// unanswered question.
if config.keys.is_locked() && !config.approver.ask_unlock().await {
record(
config,
client,
method,
kind,
Some(&identity),
audit::outcome::LOCKED,
);
return Err("the key vault is locked".to_string());
}
let keys = match config.keys.get(&identity).await {
Ok(keys) => keys,
Err(error) => {
// The key was removed while the dialog was open, or the vault still
// refuses. Either way nothing was answered.
record(
config,
client,
method,
kind,
Some(&identity),
audit::outcome::DENIED,
);
return Err(error.to_string());
}
};
record(config, client, method, kind, Some(&identity), verdict.outcome());
Ok(keys)
}
/// Record a decision and wake the pages that display it.
///
/// Metadata only: the activity log must never contain event content, plaintext
@@ -1186,6 +1235,7 @@ fn payload(params: &[String]) -> &str {
#[cfg(test)]
mod tests {
use super::*;
use super::approval::Prompt;
/// The relay to test against: `REGENT_TEST_RELAY`, or a local `nak serve`.
struct TestRelay {
@@ -1243,10 +1293,17 @@ mod tests {
/// Answers every question the same way, standing in for the UI.
fn auto_approver(decision: Decision) -> (Approver, tokio::task::JoinHandle<()>) {
let (approver, questions) = Approver::new();
let (approver, prompts) = Approver::new();
let handle = tokio::spawn(async move {
while let Ok(question) = questions.recv().await {
let _ = question.reply.send(decision).await;
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
let _ = reply.send(false).await;
}
}
}
});
(approver, handle)
@@ -1263,14 +1320,21 @@ mod tests {
where
F: Fn(&Request) -> Decision + Send + 'static,
{
let (approver, questions) = Approver::new();
let (approver, prompts) = Approver::new();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
let handle = tokio::spawn(async move {
while let Ok(question) = questions.recv().await {
let decision = decide(&question.question.request);
log.lock().unwrap().push(question.question.request.clone());
let _ = question.reply.send(decision).await;
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { question, reply } => {
let decision = decide(&question.request);
log.lock().unwrap().push(question.request.clone());
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
let _ = reply.send(false).await;
}
}
}
});
(approver, handle, seen)
@@ -1580,6 +1644,187 @@ mod tests {
.count()
}
/// A real vault holding one key, locked again afterwards.
async fn vault_with_key(passphrase: &str) -> (std::path::PathBuf, KeyStore) {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let dir = std::env::temp_dir().join(format!(
"regent-signer-vault-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
let store = KeyStore::at(dir.join("keys.json")).expect("open a fresh vault");
store
.generate_user_key("Test identity", passphrase)
.await
.expect("generate a key");
store.lock();
(dir, store)
}
/// A config whose identity keys come from a real vault, so the locked path
/// is exercised end to end. The registry starts empty; the caller approves
/// the client it wants.
fn vault_config(
relay: &str,
approver: Approver,
store: Arc<KeyStore>,
identity: PublicKey,
activity: ActivityLog,
) -> SignerConfig {
let (changes, _receiver) = async_channel::unbounded();
let names = Arc::new(Mutex::new(HashMap::from([(
identity.to_hex(),
"Test identity".to_string(),
)])));
SignerConfig {
device_keys: Keys::generate(),
keys: IdentityKeys::Store(store),
names,
default_identity: Arc::new(Mutex::new(Some(identity))),
relays: vec![relay.to_string()],
secret: "test-secret".to_string(),
approver,
extra_relays: Vec::new(),
registry: Arc::new(Mutex::new(AppRegistry::default())),
rate: RateLimiter::new(60),
activity,
changes,
}
}
/// A locked vault is refused until the user opens it, and then it signs.
#[tokio::test]
async fn a_locked_vault_refuses_until_the_user_unlocks_it() {
let (dir, store) = vault_with_key("hunter2").await;
let store = Arc::new(store);
let identity = store.list_user_keys()[0].public_key;
let client = Keys::generate();
let (approver, prompts) = Approver::new();
let unlocking = Arc::clone(&store);
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Once).await;
}
Prompt::Unlock { reply } => {
let opened = unlocking.unlock("hunter2").await.is_ok();
let _ = reply.send(opened).await;
}
}
}
});
let (log_path, log) = temp_log();
let config = vault_config(
"ws://127.0.0.1:1",
approver,
Arc::clone(&store),
identity,
log.clone(),
);
config
.registry
.lock()
.unwrap()
.approve(&bare_client(&client.public_key()), identity)
.unwrap();
assert!(store.is_locked());
let device = config.device_keys.public_key();
let answer = sign_once(&client, &device, &config, "hello").await;
assert!(
answer["result"].is_string(),
"the user opened the vault, so the event is signed: {answer}"
);
assert!(
!store.is_locked(),
"the vault stays open for the session"
);
drain.abort();
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_file(&log_path);
}
/// A locked vault the user does not open denies — and the log says `locked`
/// rather than claiming the silent answer a stored permission would give.
#[tokio::test]
async fn a_locked_vault_denies_and_is_not_logged_as_allowed() {
let (dir, store) = vault_with_key("hunter2").await;
let store = Arc::new(store);
let identity = store.list_user_keys()[0].public_key;
let client = Keys::generate();
let (approver, prompts) = Approver::new();
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Once).await;
}
// The user closes the unlock dialog without opening it.
Prompt::Unlock { reply } => {
let _ = reply.send(false).await;
}
}
}
});
let (log_path, log) = temp_log();
let config = vault_config(
"ws://127.0.0.1:1",
approver,
Arc::clone(&store),
identity,
log.clone(),
);
config
.registry
.lock()
.unwrap()
.approve(&bare_client(&client.public_key()), identity)
.unwrap();
// A stored "allow always": without the vault gate this would be answered
// silently, which is exactly what must not happen while locked.
config
.registry
.lock()
.unwrap()
.allow(&client.public_key(), Permission::Kind(1))
.unwrap();
let device = config.device_keys.public_key();
let request = client_request(&client, &device, "sign_event", sign_params(1, "hello"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
assert!(
answer["error"]
.as_str()
.unwrap_or_default()
.contains("locked"),
"the client must see that the vault is locked, got {answer}"
);
let entries = log.recent(10);
assert_eq!(entries.len(), 1, "exactly one outcome is recorded");
assert_eq!(entries[0].outcome, audit::outcome::LOCKED);
assert_ne!(
entries[0].outcome,
audit::outcome::SILENT,
"a request the vault refused is never logged as a silent answer"
);
drain.abort();
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_file(&log_path);
}
#[tokio::test]
async fn signing_asks_and_a_denial_reaches_the_client() {
let client = Keys::generate();
+38 -2
View File
@@ -71,12 +71,48 @@ impl AppState {
*connecting.store.borrow_mut() = Some(Arc::clone(&store));
connecting.refresh_identities();
}
Err(error) => eprintln!("regent: the keyring is unavailable: {error}"),
Err(error) => eprintln!("regent: the key vault is unavailable: {error}"),
});
state.watch_auto_lock();
state
}
/// Lock the vault once it has been open longer than the configured timeout.
///
/// A **hard** timeout measured from the unlock, not an idle timer that
/// request traffic resets: otherwise a client that keeps asking would hold
/// the keys open forever. The timer only ticks while a vault exists.
fn watch_auto_lock(self: &Rc<Self>) {
let state = Rc::clone(self);
glib::timeout_add_seconds_local(30, move || {
let timeout = Config::new().lock_timeout();
if timeout == 0 {
return glib::ControlFlow::Continue;
}
let Some(store) = state.store() else {
return glib::ControlFlow::Continue;
};
let expired = store
.unlocked_at()
.map(|at| at.elapsed() >= std::time::Duration::from_secs(timeout as u64))
.unwrap_or(false);
if expired {
store.lock();
eprintln!("regent: the key vault locked itself after {timeout}s");
state.notify();
}
glib::ControlFlow::Continue
});
}
/// Whether the vault still needs the passphrase.
pub fn is_locked(&self) -> bool {
self.store()
.map(|store| store.is_locked())
.unwrap_or(false)
}
pub fn store(&self) -> Option<Arc<KeyStore>> {
self.store.borrow().clone()
}
@@ -140,7 +176,7 @@ impl AppState {
let configured = Config::new().current_identity();
let state = Rc::clone(self);
runtime::spawn(
async move { store.list_user_keys().await },
async move { Ok::<_, String>(store.list_user_keys()) },
move |result| match result {
Ok(keys) => {
// The **live** selection wins over the setting snapshot: a
+1 -1
View File
@@ -1,7 +1,7 @@
//! The registry of applications the user has approved.
//!
//! Not secret, so it is a plain JSON file under the config directory — unlike
//! the keys, which live in the keyring.
//! the identity keys, which are NIP-49 encrypted in `keys.json`.
use std::collections::BTreeSet;
use std::path::PathBuf;
+2
View File
@@ -47,6 +47,8 @@ pub mod outcome {
/// Answered from a stored permission, without asking.
pub const SILENT: &str = "allowed-silently";
pub const LOGGED_OUT: &str = "logged-out";
/// Refused because the key vault was locked and was not opened.
pub const LOCKED: &str = "locked";
}
/// The current Unix time in seconds, for [`Entry::at`].
+684 -240
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,4 +1,5 @@
//! Persistent state: the keyring, the application registry, and the activity log.
//! Persistent state: the encrypted key vault, the application registry, and the
//! activity log.
pub mod apps;
pub mod audit;
+3
View File
@@ -191,6 +191,9 @@ fn outcome_label(outcome: &str) -> &'static str {
audit::outcome::ALLOWED_ALWAYS => "allowed always",
audit::outcome::SILENT => "allowed silently",
audit::outcome::LOGGED_OUT => "logged out",
// A refused request the vault never opened: not a success, and the log
// must not read like one.
audit::outcome::LOCKED => "locked",
_ => "handled",
}
}
+115 -7
View File
@@ -5,23 +5,46 @@
//! Pango markup — so an application cannot forge formatting that looks like
//! Regent's own interface.
use std::sync::Arc;
use async_channel::Receiver;
use nostr::nips::nip19::ToBech32;
use zeroize::Zeroizing;
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::signer::approval::{ApprovalRequest, Decision, Question, Request};
use crate::runtime;
use crate::signer::approval::{Decision, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{kind, plain};
/// Start draining questions: each one becomes a dialog, and the answer goes back
/// to the responder. Anything unanswered is a denial.
pub fn install(questions: Receiver<ApprovalRequest>, widget: gtk::Widget) {
/// Start draining prompts: each one becomes a dialog, and the answer goes back
/// to the responder. Anything unanswered is a denial — and an unanswered unlock
/// leaves the vault locked.
pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::Rc<AppState>) {
glib::MainContext::default().spawn_local(async move {
while let Ok(pending) = questions.recv().await {
let decision = present_question(&widget, &pending.question).await;
let _ = pending.reply.send(decision).await;
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { question, reply } => {
let decision = present_question(&widget, &question).await;
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
let unlocked = match state.store() {
Some(store) => present_unlock(&widget, store).await,
None => false,
};
if unlocked {
// Only `notify` reaches the header lock button and the
// keys page's vault rows; `notify_changes` does not.
state.notify();
}
let _ = reply.send(unlocked).await;
}
}
}
});
}
@@ -98,6 +121,91 @@ pub async fn present_question(
answer.recv().await.unwrap_or(Decision::Deny)
}
/// Ask for the vault passphrase and open it.
///
/// A locked vault fails closed: cancelling, closing the window or a missing
/// store leaves it locked, exactly like an unanswered approval question.
pub async fn present_unlock(widget: &impl IsA<gtk::Widget>, store: Arc<KeyStore>) -> bool {
if !store.is_locked() {
return true;
}
loop {
let Some(passphrase) = ask_passphrase(widget).await else {
return false;
};
let (sender, answer) = async_channel::bounded(1);
{
let store = Arc::clone(&store);
runtime::spawn(
async move { store.unlock(&passphrase).await },
move |result| {
let _ = sender.try_send(result);
},
);
}
match answer.recv().await {
Ok(Ok(())) => return true,
Ok(Err(error)) => {
// Wrong passphrase, or an unreadable vault: say so and ask again.
let dialog = adw::AlertDialog::builder()
.heading("Could not unlock")
.body(error)
.build();
plain::dialog(&dialog);
dialog.add_response("close", "Try again");
dialog.set_default_response(Some("close"));
let (sender, answer) = async_channel::bounded(1);
dialog.connect_response(None, move |_, _| {
let _ = sender.try_send(());
});
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
// Wait for the acknowledgement so the next prompt does not
// stack on top of it.
let _ = answer.recv().await;
}
Err(_) => return false,
}
}
}
/// One passphrase dialog. `None` when the user cancelled.
///
/// Unlike an approval question this *does* have a default response: the user is
/// typing the passphrase themselves, and an empty submit simply fails and asks
/// again. It never answers a client's request on the user's behalf.
async fn ask_passphrase(widget: &impl IsA<gtk::Widget>) -> Option<Zeroizing<String>> {
let entry = adw::PasswordEntryRow::builder().title("Passphrase").build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&entry);
let dialog = adw::AlertDialog::builder()
.heading("Unlock the key vault")
.body("Your identity keys are stored encrypted with your passphrase.")
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("unlock", "Unlock");
dialog.set_default_response(Some("unlock"));
dialog.set_response_appearance("unlock", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
let (sender, answer) = async_channel::bounded(1);
dialog.connect_response(None, move |_, response| {
let _ = sender.try_send(response == "unlock");
});
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
if answer.recv().await.unwrap_or(false) {
Some(Zeroizing::new(entry.text().to_string()))
} else {
None
}
}
fn heading(request: &Request) -> String {
match request {
Request::Pair { .. } => "Connect an application?".to_string(),
+321 -33
View File
@@ -1,8 +1,9 @@
//! The keys page: the identity keys (named, several of them) and the device key.
//!
//! Creating, importing, renaming, exporting and removing a key all happen here;
//! the selected identity (used for new pairings and by the header switcher in
//! M7b) is chosen from the same list.
//! the selected identity (used for new pairings and by the header switcher) is
//! chosen from the same list. The vault itself is managed here too: its
//! passphrase, the auto-lock timeout, and "Lock now".
use std::cell::RefCell;
use std::rc::Rc;
@@ -15,10 +16,22 @@ use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::runtime;
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::plain;
use crate::ui::{approval, plain};
/// The auto-lock choices: the timeout in seconds, and what to call it. `0` means
/// never lock, which is the user's call to make — but not the default.
const AUTO_LOCK: [(u32, &str); 6] = [
(60, "1 minute"),
(300, "5 minutes"),
(900, "15 minutes"),
(1800, "30 minutes"),
(3600, "1 hour"),
(0, "Never"),
];
/// Handles the callbacks need; cloned per closure.
#[derive(Clone)]
@@ -26,6 +39,10 @@ struct Handles {
stack: gtk::Stack,
list: adw::PreferencesGroup,
device: adw::ActionRow,
passphrase: adw::ActionRow,
passphrase_button: gtk::Button,
lock_button: gtk::Button,
auto_lock: adw::ComboRow,
}
/// The rows currently in the list, so a reload can remove exactly them.
@@ -45,7 +62,7 @@ impl KeysView {
let stack = gtk::Stack::builder().vexpand(true).build();
let loading = adw::StatusPage::builder()
.title("Connecting to the keyring…")
.title("Opening the key vault…")
.child(&adw::Spinner::new())
.build();
stack.add_named(&loading, Some("loading"));
@@ -68,8 +85,8 @@ impl KeysView {
.icon_name("security-high-symbolic")
.title("No key yet")
.description(
"Create a Nostr identity key or import one you already have. It is kept in \
the system keyring and never written to disk by Regent.",
"Create a Nostr identity key or import one you already have. Your identity \
keys are stored encrypted on this computer and need your passphrase to sign.",
)
.child(&actions)
.build();
@@ -91,7 +108,10 @@ impl KeysView {
.build();
device_group.add(&device);
let add_group = adw::PreferencesGroup::builder().title("Add a key").build();
let create_row = plain::row("Create a new identity key", "Generate one in the keyring");
let create_row = plain::row(
"Create a new identity key",
"Generate one and store it encrypted",
);
let create_button = gtk::Button::builder()
.label("Create")
.valign(gtk::Align::Center)
@@ -108,9 +128,46 @@ impl KeysView {
add_group.add(&create_row);
add_group.add(&import_row);
let vault_group = adw::PreferencesGroup::builder()
.title("Vault")
.description(
"Identity keys are encrypted with NIP-49 under one passphrase. Regent keeps \
the passphrase out of memory and locks the vault again after the timeout \
below.",
)
.build();
let passphrase = plain::row("Passphrase", "—");
let passphrase_button = gtk::Button::builder()
.label("Change…")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
passphrase.add_suffix(&passphrase_button);
let lock_row = plain::row(
"Lock now",
"Require the passphrase before the next signature",
);
let lock_button = gtk::Button::builder()
.label("Lock")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
lock_row.add_suffix(&lock_button);
let labels: Vec<&str> = AUTO_LOCK.iter().map(|(_, label)| *label).collect();
let auto_lock = adw::ComboRow::builder()
.title("Auto-lock after")
.subtitle("How long the vault stays open once it is unlocked")
.model(&gtk::StringList::new(&labels))
.build();
vault_group.add(&passphrase);
vault_group.add(&auto_lock);
vault_group.add(&lock_row);
let page = adw::PreferencesPage::new();
page.add(&list);
page.add(&add_group);
page.add(&vault_group);
page.add(&device_group);
stack.add_named(&page, Some("loaded"));
stack.set_visible_child_name("loading");
@@ -119,6 +176,10 @@ impl KeysView {
stack,
list,
device,
passphrase,
passphrase_button,
lock_button,
auto_lock,
};
let rows: Rows = Rc::new(RefCell::new(Vec::new()));
let widget: gtk::Widget = handles.stack.clone().upcast();
@@ -132,6 +193,35 @@ impl KeysView {
button.connect_clicked(move |_| present_import(handles.clone(), Rc::clone(&state)));
}
{
let (state, handles) = (Rc::clone(&state), handles.clone());
handles.passphrase_button.clone().connect_clicked(move |_| {
present_change_passphrase(handles.clone(), Rc::clone(&state))
});
}
{
let state = Rc::clone(&state);
handles.lock_button.clone().connect_clicked(move |_| {
if let Some(store) = state.store() {
store.lock();
eprintln!("regent: the key vault is locked");
state.notify();
}
});
}
{
handles.auto_lock.clone().connect_selected_notify(move |row| {
if let Some((seconds, _)) = AUTO_LOCK.get(row.selected() as usize) {
let config = Config::new();
// Idempotent: reload sets the selection too, and writing the
// same value back must not loop.
if config.lock_timeout() != *seconds {
config.set_lock_timeout(*seconds);
}
}
});
}
// Reload on key changes and on a selection change.
{
let (listener_state, handles, rows) =
@@ -157,6 +247,10 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
let names = state.names();
let names = names.lock().unwrap().clone();
let current = state.current_identity().map(|key| key.to_hex());
reload_vault(state, handles);
reload_device(handles.clone(), state.store());
if names.is_empty() {
handles.stack.set_visible_child_name("empty");
return;
@@ -180,8 +274,30 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
handles.list.add(&row);
rows.borrow_mut().push(row);
}
}
reload_device(handles.clone(), state.store());
/// Reflect the vault's state: which actions need it open, and the timeout.
fn reload_vault(state: &Rc<AppState>, handles: &Handles) {
let locked = state
.store()
.map(|store| store.is_locked())
.unwrap_or(false);
handles.passphrase_button.set_sensitive(!locked);
handles.lock_button.set_sensitive(!locked);
handles.passphrase.set_subtitle(if locked {
"Locked — unlock to change it"
} else {
"Encrypts every identity key"
});
let seconds = Config::new().lock_timeout();
// The combo is the only UI for this setting, so an out-of-range value (set
// by hand) falls back to the default rather than showing nothing selected.
let index = AUTO_LOCK
.iter()
.position(|(value, _)| *value == seconds)
.unwrap_or(2);
handles.auto_lock.set_selected(index as u32);
}
fn reload_device(handles: Handles, store: Option<Arc<KeyStore>>) {
@@ -189,7 +305,7 @@ fn reload_device(handles: Handles, store: Option<Arc<KeyStore>>) {
return;
};
runtime::spawn(
async move { store.device_key().await },
async move { store.device_key() },
move |result| match result {
Ok(keys) => set_public_key(&handles.device, &keys.public_key()),
Err(error) => {
@@ -308,15 +424,84 @@ fn set_public_key(row: &adw::ActionRow, public_key: &PublicKey) {
row.set_subtitle(&public_key.to_bech32().unwrap_or_default());
}
/// A passphrase field for the add/import dialogs, plus a confirmation when this
/// is the call that *sets* the vault passphrase.
struct PassphraseFields {
passphrase: adw::PasswordEntryRow,
confirm: Option<adw::PasswordEntryRow>,
}
impl PassphraseFields {
fn new(first: bool) -> Self {
let passphrase = adw::PasswordEntryRow::builder()
.title(if first {
"Choose a passphrase"
} else {
"Vault passphrase"
})
.build();
let confirm = first.then(|| {
adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build()
});
Self { passphrase, confirm }
}
fn append_to(&self, list: &gtk::ListBox) {
list.append(&self.passphrase);
if let Some(confirm) = &self.confirm {
list.append(confirm);
}
}
/// The typed passphrase, or an error to show instead of proceeding.
fn value(&self) -> Result<String, String> {
let passphrase = self.passphrase.text().to_string();
if passphrase.chars().count() < 8 {
return Err("Use a passphrase of at least 8 characters.".to_string());
}
if let Some(confirm) = &self.confirm {
if confirm.text().to_string() != passphrase {
return Err("The two passphrases do not match.".to_string());
}
}
Ok(passphrase)
}
}
/// The vault is opened for these dialogs; an import that sets the passphrase
/// explains the risk.
const NEW_VAULT_NOTE: &str = "Choose a passphrase for the key vault. Every identity key is \
stored encrypted under it, and it is needed to sign. There is no recovery if you forget it.";
fn present_create(handles: Handles, state: Rc<AppState>) {
let Some(store) = state.store() else {
return;
};
let first = !store.has_vault();
let count = state.names().lock().unwrap().len() + 1;
let entry = gtk::Entry::builder()
let name = adw::EntryRow::builder()
.title("Name")
.text(format!("Identity {count}"))
.build();
let fields = PassphraseFields::new(first);
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&name);
fields.append_to(&list);
let dialog = adw::AlertDialog::builder()
.heading("Create an identity key")
.body("The key is generated in the keyring and never written to disk by Regent.")
.extra_child(&entry)
.body(if first {
NEW_VAULT_NOTE
} else {
"The new key is encrypted under your vault passphrase."
})
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
@@ -326,20 +511,21 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
dialog.set_close_response("cancel");
{
let entry = entry.clone();
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "create" {
return;
}
let Some(store) = state.store() else {
return;
let passphrase = match fields.value() {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
let name = defaulted_name(&entry);
let name = defaulted_name(&name.text().to_string());
let after = Rc::clone(&state);
let handles = handles.clone();
let store = Arc::clone(&store);
runtime::spawn(
async move { store.generate_user_key(&name).await },
async move { store.generate_user_key(&name, &passphrase).await },
move |result| match result {
Ok(_) => after.refresh_identities(),
Err(error) => report_error(&handles, &error),
@@ -351,22 +537,33 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
}
fn present_import(handles: Handles, state: Rc<AppState>) {
let Some(store) = state.store() else {
return;
};
let first = !store.has_vault();
let entry = adw::EntryRow::builder()
.title("nsec, hex, or ncryptsec")
.build();
let password = adw::PasswordEntryRow::builder()
let import_password = adw::PasswordEntryRow::builder()
.title("Password (ncryptsec only)")
.build();
let fields = PassphraseFields::new(first);
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&entry);
list.append(&password);
list.append(&import_password);
fields.append_to(&list);
let dialog = adw::AlertDialog::builder()
.heading("Import an identity key")
.body("Leave this Regent's other identity keys untouched.")
.body(if first {
NEW_VAULT_NOTE
} else {
"The imported key is re-encrypted under your vault passphrase."
})
.extra_child(&list)
.build();
plain::dialog(&dialog);
@@ -377,26 +574,29 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
dialog.set_close_response("cancel");
{
let (entry, password) = (entry.clone(), password.clone());
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "import" {
return;
}
let Some(store) = state.store() else {
return;
let passphrase = match fields.value() {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
let text = entry.text().to_string();
let password = password.text().to_string();
let import_password = import_password.text().to_string();
let name = format!("Imported {count}", count = state.names().lock().unwrap().len() + 1);
let after = Rc::clone(&state);
let handles = handles.clone();
let store = Arc::clone(&store);
runtime::spawn(
async move {
if text.starts_with("ncryptsec1") {
store.import_user_key_encrypted(&name, &text, &password).await
store
.import_user_key_encrypted(&name, &text, &import_password, &passphrase)
.await
} else {
store.import_user_key(&name, &text).await
store.import_user_key(&name, &text, &passphrase).await
}
},
move |result| match result {
@@ -409,6 +609,87 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
dialog.present(toplevel(&handles).as_ref());
}
/// Run `then` once the vault is open, asking for the passphrase first if needed.
fn with_unlocked<F: FnOnce() + 'static>(handles: &Handles, state: &Rc<AppState>, then: F) {
let Some(store) = state.store() else {
return;
};
if !store.is_locked() {
then();
return;
}
let widget: gtk::Widget = handles.stack.clone().upcast();
let state = Rc::clone(state);
glib::MainContext::default().spawn_local(async move {
if approval::present_unlock(&widget, store).await {
// The vault just opened: the header button and the vault rows only
// hear about it through `notify`.
state.notify();
then();
}
});
}
fn present_change_passphrase(handles: Handles, state: Rc<AppState>) {
let new = adw::PasswordEntryRow::builder().title("New passphrase").build();
let confirm = adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&new);
list.append(&confirm);
let dialog = adw::AlertDialog::builder()
.heading("Change the vault passphrase")
.body(
"Every identity key is re-encrypted under the new passphrase. There is no \
recovery if you forget it.",
)
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("change", "Change");
dialog.set_default_response(Some("change"));
dialog.set_response_appearance("change", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
{
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "change" {
return;
}
let passphrase = new.text().to_string();
if passphrase.chars().count() < 8 {
return report_error(&handles, "Use a passphrase of at least 8 characters.");
}
if confirm.text().to_string() != passphrase {
return report_error(&handles, "The two passphrases do not match.");
}
let Some(store) = state.store() else {
return;
};
let after = Rc::clone(&state);
let handles = handles.clone();
runtime::spawn(
async move { store.change_passphrase(&passphrase).await },
move |result| match result {
Ok(()) => {
eprintln!("regent: the key vault passphrase was changed");
after.notify();
}
Err(error) => report_error(&handles, &error),
},
);
});
}
dialog.present(toplevel(&handles).as_ref());
}
fn present_rename(
handles: Handles,
state: Rc<AppState>,
@@ -437,11 +718,11 @@ fn present_rename(
let Some(store) = state.store() else {
return;
};
let name = defaulted_name(&entry);
let name = defaulted_name(&entry.text().to_string());
let after = Rc::clone(&state);
let handles = handles.clone();
runtime::spawn(
async move { store.rename_user_key(&public_key, &name).await },
async move { store.rename_user_key(&public_key, &name) },
move |result| match result {
Ok(_) => after.refresh_identities(),
Err(error) => report_error(&handles, &error),
@@ -453,6 +734,14 @@ fn present_rename(
}
fn present_export(handles: Handles, state: Rc<AppState>, public_key: PublicKey) {
// Exporting needs the key itself, so the vault has to be open first.
let (h, s) = (handles.clone(), Rc::clone(&state));
with_unlocked(&handles, &state, move || {
present_export_dialog(h, s, public_key)
});
}
fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: PublicKey) {
let password = adw::PasswordEntryRow::builder().title("Password").build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
@@ -533,7 +822,7 @@ fn present_remove(
) {
let paired = state.registry().lock().unwrap().list_for(public_key);
let body = if paired.is_empty() {
format!("Remove “{name}” from the keyring? This cannot be undone.")
format!("Remove “{name}” from this computer? This cannot be undone.")
} else {
let apps: Vec<String> = paired
.iter()
@@ -569,7 +858,7 @@ fn present_remove(
runtime::spawn(
async move {
registry.lock().unwrap().clear_for(public_key)?;
store.forget_user_key(&public_key).await?;
store.forget_user_key(&public_key)?;
Ok::<(), crate::store::keys::Error>(())
},
move |result| match result {
@@ -582,9 +871,8 @@ fn present_remove(
dialog.present(toplevel(&handles).as_ref());
}
fn defaulted_name(entry: &gtk::Entry) -> String {
let name = entry.text().to_string();
let name = name.trim();
fn defaulted_name(text: &str) -> String {
let name = text.trim();
if name.is_empty() {
"Identity key".to_string()
} else {
+24 -11
View File
@@ -34,6 +34,7 @@ struct Handles {
toggle: gtk::Button,
pair: gtk::Button,
signing_as: adw::ActionRow,
vault: adw::ActionRow,
}
/// The toplevel, resolved lazily: a view is not in a window when it is built.
@@ -81,6 +82,7 @@ impl SignerView {
uri.add_suffix(&copy);
let device = plain::row("Device key", "—");
let signing_as = plain::row("New connections", "—");
let vault = plain::row("Key vault", "—");
let group = adw::PreferencesGroup::builder()
.title("Pairing")
@@ -90,6 +92,7 @@ impl SignerView {
group.add(&uri);
group.add(&device);
group.add(&signing_as);
group.add(&vault);
// The client-initiated direction: the application shows a
// `nostrconnect://` string and waits for the signer to answer it.
@@ -147,20 +150,25 @@ impl SignerView {
toggle,
pair,
signing_as,
vault,
};
let widget: gtk::Widget = handles.stack.clone().upcast();
update_signing_as(&handles, &state);
update_state(&handles, &state);
{
let (listener_handles, listener_state) = (handles.clone(), Rc::clone(&state));
state.listen_changes(move || update_signing_as(&listener_handles, &listener_state));
state.listen(move || update_state(&listener_handles, &listener_state));
}
{
let (listener_handles, listener_state) = (handles.clone(), Rc::clone(&state));
state.listen_changes(move || update_state(&listener_handles, &listener_state));
}
// Approval questions are answered on the main loop; the responder waits
// on the other end of this channel.
let (approver, questions) = Approver::new();
crate::ui::approval::install(questions, widget.clone());
// Approval questions and unlock prompts are answered on the main loop;
// the responder waits on the other end of this channel.
let (approver, prompts) = Approver::new();
crate::ui::approval::install(prompts, widget.clone(), Rc::clone(&state));
let running: Running = Rc::new(RefCell::new(State::Stopped));
@@ -212,7 +220,7 @@ impl SignerView {
});
}
// React to the keyring becoming available, and to keys being changed.
// React to the vault becoming available, and to keys being changed.
{
let handles = handles.clone();
let signer_running = Rc::clone(&running);
@@ -232,7 +240,7 @@ impl SignerView {
);
let approver = listener_approver.clone();
runtime::spawn(
async move { store.list_user_keys().await },
async move { Ok::<_, String>(store.list_user_keys()) },
move |result| match result {
Ok(keys) if keys.is_empty() => show_empty(&handles),
Ok(_) => start(handles, state, running, approver, Vec::new(), None),
@@ -246,8 +254,8 @@ impl SignerView {
}
}
/// Show which identity a new pairing would use.
fn update_signing_as(handles: &Handles, state: &Rc<AppState>) {
/// Show which identity a new pairing would use, and whether the vault is open.
fn update_state(handles: &Handles, state: &Rc<AppState>) {
let subtitle = match state.current_identity() {
Some(key) => {
let name = state.identity_label(&key);
@@ -257,6 +265,11 @@ fn update_signing_as(handles: &Handles, state: &Rc<AppState>) {
None => "no identity key yet".to_string(),
};
handles.signing_as.set_subtitle(&subtitle);
handles.vault.set_subtitle(if state.is_locked() {
"Locked — the passphrase is needed to sign"
} else {
"Unlocked"
});
}
fn show_empty(handles: &Handles) {
@@ -510,7 +523,7 @@ fn begin_pairing(
if state.store().is_none() {
report_error(
&handles,
"The keyring is not ready yet; try again in a moment.",
"The key vault is not ready yet; try again in a moment.",
);
return;
}
+29
View File
@@ -83,6 +83,35 @@ impl Window {
// identities are managed, so it is hidden there.
let identity_switcher = IdentitySwitcher::new(Rc::clone(&state), stack.clone());
header_bar.pack_end(identity_switcher.button());
// The vault's lock state, always visible, to the left of the switcher.
let lock_button = gtk::Button::builder()
.icon_name("changes-prevent-symbolic")
.tooltip_text("Lock the key vault")
.css_classes(["flat"])
.build();
lock_button.set_action_name(Some("app.lock"));
header_bar.pack_end(&lock_button);
{
let button = lock_button.clone();
let listener_state = Rc::clone(&state);
state.listen(move || {
let ready = listener_state.store().is_some();
let locked = listener_state.is_locked();
// Before the vault is open there is nothing to lock or unlock.
button.set_sensitive(ready);
button.set_icon_name(if locked {
"changes-allow-symbolic"
} else {
"changes-prevent-symbolic"
});
button.set_tooltip_text(Some(if locked {
"Unlock the key vault"
} else {
"Lock the key vault"
}));
});
}
{
let identity_switcher = Rc::clone(&identity_switcher);
stack.connect_visible_child_name_notify(move |stack| {