Add M6: headless mode and CLI pairing
This commit is contained in:
10 files changed
+680
-20
No files matched your search
Generated
+1
@@ -1920,6 +1920,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"url",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
|
||||
+2
-1
@@ -13,10 +13,11 @@ gtk = { package = "gtk4", version = "0.11", features = ["v4_24"] }
|
||||
libadwaita = { version = "0.9", features = ["v1_10"] }
|
||||
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"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal"] }
|
||||
async-channel = "2"
|
||||
serde_json = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
+44
-1
@@ -26,7 +26,7 @@ export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
|
||||
mkdir -p "$HOME/.local/share/keyrings"
|
||||
|
||||
cleanup() {
|
||||
kill ${APP:-} ${RELAY:-} ${BWAY:-} 2>/dev/null
|
||||
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} 2>/dev/null
|
||||
wait 2>/dev/null
|
||||
rm -rf "$TMP_HOME"
|
||||
}
|
||||
@@ -87,6 +87,49 @@ check $? "the app started the signer ($(grep -m1 'signer listening' "$TMP_HOME/a
|
||||
[ -n "$(secret-tool lookup application org.kosmos.raucao.Regent kind device 2>/dev/null)" ]
|
||||
check $? "a device key was created in the keyring"
|
||||
|
||||
# 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.
|
||||
kill "$APP" 2>/dev/null
|
||||
sleep 1
|
||||
APP=
|
||||
|
||||
printf '\n== headless mode and CLI pairing ==\n'
|
||||
CLIENT=$(nak key public "$(nak key generate)")
|
||||
# A real client is subscribed and waiting for its connect response — without a
|
||||
# subscriber, `nak serve` mutes the response.
|
||||
nak req --stream -k 24133 -p "$CLIENT" "ws://127.0.0.1:$PORT" \
|
||||
>"$TMP_HOME/subscriber.log" 2>&1 &
|
||||
SUBSCRIBER=$!
|
||||
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 &
|
||||
HEADLESS=$!
|
||||
sleep 5
|
||||
|
||||
grep -q 'signer listening' "$TMP_HOME/headless.log"
|
||||
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"
|
||||
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"
|
||||
check $? "the pairing auto-granted nothing"
|
||||
|
||||
grep -q "$CLIENT" "$TMP_HOME/subscriber.log"
|
||||
check $? "the client received the connect response"
|
||||
|
||||
kill "$HEADLESS" "$SUBSCRIBER" 2>/dev/null
|
||||
HEADLESS=
|
||||
SUBSCRIBER=
|
||||
|
||||
printf '\n'
|
||||
if [ "$fails" = 0 ]; then
|
||||
printf 'all checks passed\n'
|
||||
|
||||
@@ -25,6 +25,7 @@ cargo_build = custom_target(binary_name,
|
||||
'src/main.rs',
|
||||
'src/application.rs',
|
||||
'src/config.rs',
|
||||
'src/headless.rs',
|
||||
'src/runtime.rs',
|
||||
'src/signer/approval.rs',
|
||||
'src/signer/mod.rs',
|
||||
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
//! Headless mode: run the signer with no window.
|
||||
//!
|
||||
//! Used by `regent --headless` and `regent --pair nostrconnect://…`. There is
|
||||
//! no UI, so **anything not covered by a stored permission is denied** — the
|
||||
//! approval bridge's questions are answered `Deny` immediately rather than
|
||||
//! waiting out the timeout. Pre-approve in the GUI, then run headless.
|
||||
//!
|
||||
//! Deliberately not a `GtkApplication`: headless must work with no display, and
|
||||
//! nothing here needs GTK. It is a plain tokio program.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use glib::prelude::ToVariant;
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::runtime;
|
||||
use crate::signer::approval::{Approver, Decision};
|
||||
use crate::signer::{ClientPairing, Signer, SignerConfig, parse_client_uri};
|
||||
use crate::store::apps::AppRegistry;
|
||||
use crate::store::audit::{self, ActivityLog, Entry};
|
||||
use crate::store::keys::KeyStore;
|
||||
use crate::APP_ID;
|
||||
|
||||
/// Run headless. `pair` is a `nostrconnect://` URI when `--pair` was given.
|
||||
pub fn run(pair: Option<String>) -> glib::ExitCode {
|
||||
match runtime::block_on(serve(pair.as_deref())) {
|
||||
Ok(()) => glib::ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("regent: {error}");
|
||||
glib::ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(pair: 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.
|
||||
if another_instance_running()? {
|
||||
return Err("Regent is already running".to_string());
|
||||
}
|
||||
|
||||
// Parse the URI before touching the keyring: a bad argument fails fast.
|
||||
let pairing = match pair {
|
||||
Some(uri) => Some(parse_client_uri(uri).map_err(|error| error.to_string())?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let store = KeyStore::connect()
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
if store
|
||||
.user_key()
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
.is_none()
|
||||
{
|
||||
return Err(
|
||||
"no identity key is stored; create or import one in the GUI first".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
// No window: deny everything the user has not already allowed.
|
||||
let (approver, questions) = Approver::new();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(question) = questions.recv().await {
|
||||
let _ = question.reply.send(Decision::Deny).await;
|
||||
}
|
||||
});
|
||||
|
||||
let settings = Config::new();
|
||||
let registry = Arc::new(Mutex::new(AppRegistry::load()));
|
||||
let activity = ActivityLog::new();
|
||||
// Nobody drains this in headless mode; a full channel just coalesces.
|
||||
let (changes, _changes_rx) = async_channel::bounded(1);
|
||||
|
||||
let mut config = SignerConfig::from_store(
|
||||
&store,
|
||||
settings.relays(),
|
||||
approver,
|
||||
Arc::clone(®istry),
|
||||
settings.auto_approve_limit(),
|
||||
activity.clone(),
|
||||
changes,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
if let Some(pairing) = &pairing {
|
||||
config.extra_relays = pairing
|
||||
.relays
|
||||
.iter()
|
||||
.map(|relay| relay.to_string())
|
||||
.collect();
|
||||
}
|
||||
|
||||
let signer = Signer::start(config)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
||||
eprintln!(
|
||||
"regent: signer listening on {} relay(s) as {}",
|
||||
signer.relay_count(),
|
||||
signer.device_public_key().to_bech32().unwrap_or_default()
|
||||
);
|
||||
|
||||
if let Some(pairing) = &pairing {
|
||||
finish_pairing(&signer, ®istry, &activity, pairing).await?;
|
||||
}
|
||||
|
||||
wait_for_shutdown().await;
|
||||
signer.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Register the client and send it the `connect` response. Running `--pair` is
|
||||
/// the user's consent, so nothing is asked; permissions are never auto-granted.
|
||||
async fn finish_pairing(
|
||||
signer: &Signer,
|
||||
registry: &Arc<Mutex<AppRegistry>>,
|
||||
activity: &ActivityLog,
|
||||
pairing: &ClientPairing,
|
||||
) -> Result<(), String> {
|
||||
// A re-pair of an already-approved client must not lose its stored
|
||||
// permissions if the response cannot be delivered, so only roll back what
|
||||
// this run added.
|
||||
let was_approved = registry.lock().unwrap().contains(&pairing.client);
|
||||
registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&pairing.client_info())
|
||||
.map_err(|error| format!("could not record the pairing: {error}"))?;
|
||||
|
||||
if let Err(error) = signer.complete_pairing(pairing).await {
|
||||
rollback_pairing(registry, &pairing.client, was_approved);
|
||||
return Err(format!("pairing failed: {error}"));
|
||||
}
|
||||
|
||||
activity.record(&Entry {
|
||||
at: audit::now(),
|
||||
app: pairing.client.to_hex(),
|
||||
name: pairing.name.clone(),
|
||||
method: "connect".to_string(),
|
||||
kind: None,
|
||||
outcome: audit::outcome::PAIRED.to_string(),
|
||||
});
|
||||
|
||||
let name = pairing
|
||||
.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| "an unnamed application".to_string());
|
||||
let asked = pairing
|
||||
.requested
|
||||
.as_deref()
|
||||
.map(|perms| format!(" — it asked for {perms}"))
|
||||
.unwrap_or_default();
|
||||
println!(
|
||||
"regent: paired with {name} ({}){asked}",
|
||||
pairing.client.to_bech32().unwrap_or_default()
|
||||
);
|
||||
println!(
|
||||
"regent: headless mode denies anything not covered by a stored permission; \
|
||||
approve permissions in the GUI first"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo a pairing whose response could not be delivered: revoke the client
|
||||
/// **only if this run is what approved it**, so a re-pair never destroys
|
||||
/// existing permissions on a network blip.
|
||||
fn rollback_pairing(registry: &Arc<Mutex<AppRegistry>>, client: &PublicKey, was_approved: bool) {
|
||||
if was_approved {
|
||||
return;
|
||||
}
|
||||
let _ = registry.lock().unwrap().revoke(client);
|
||||
}
|
||||
|
||||
/// 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".
|
||||
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 reply = connection
|
||||
.call_sync(
|
||||
Some("org.freedesktop.DBus"),
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameHasOwner",
|
||||
Some(&(APP_ID,).to_variant()),
|
||||
None,
|
||||
gtk::gio::DBusCallFlags::NONE,
|
||||
-1,
|
||||
gtk::gio::Cancellable::NONE,
|
||||
)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let (owned,): (bool,) = reply.get().ok_or("unexpected NameHasOwner reply")?;
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::signer::approval::ClientInfo;
|
||||
use crate::store::apps::Permission;
|
||||
use nostr::prelude::Keys;
|
||||
|
||||
fn registry_with(kind: Option<u16>) -> (Arc<Mutex<AppRegistry>>, PublicKey) {
|
||||
let keys = Keys::generate();
|
||||
let mut registry = AppRegistry::default();
|
||||
registry
|
||||
.approve(&ClientInfo {
|
||||
public_key: keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.unwrap();
|
||||
if let Some(kind) = kind {
|
||||
registry
|
||||
.allow(&keys.public_key(), Permission::Kind(kind))
|
||||
.unwrap();
|
||||
}
|
||||
(Arc::new(Mutex::new(registry)), keys.public_key())
|
||||
}
|
||||
|
||||
/// A re-pair that cannot deliver its response must not delete an existing
|
||||
/// approval or its permissions.
|
||||
#[test]
|
||||
fn a_failed_repair_keeps_an_existing_permission() {
|
||||
let (registry, client) = registry_with(Some(1));
|
||||
|
||||
rollback_pairing(®istry, &client, true);
|
||||
|
||||
let guard = registry.lock().unwrap();
|
||||
assert!(guard.contains(&client), "the app must survive");
|
||||
assert!(guard.permits(&client, &Permission::Kind(1)));
|
||||
}
|
||||
|
||||
/// A first pairing that fails removes the client it had just added.
|
||||
#[test]
|
||||
fn a_failed_first_pairing_revokes_the_client() {
|
||||
let (registry, client) = registry_with(None);
|
||||
|
||||
rollback_pairing(®istry, &client, false);
|
||||
|
||||
assert!(!registry.lock().unwrap().contains(&client));
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_shutdown() {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
|
||||
let mut terminate = match signal(SignalKind::terminate()) {
|
||||
Ok(stream) => stream,
|
||||
Err(_) => {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {}
|
||||
_ = terminate.recv() => {}
|
||||
}
|
||||
}
|
||||
+66
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
mod application;
|
||||
mod config;
|
||||
mod headless;
|
||||
mod runtime;
|
||||
mod signer;
|
||||
mod state;
|
||||
@@ -18,17 +19,80 @@ pub const APP_ID: &str = "org.kosmos.raucao.Regent";
|
||||
pub const RESOURCE_PATH: &str = "/org/kosmos/raucao/Regent";
|
||||
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>]
|
||||
regent --version
|
||||
regent --help
|
||||
|
||||
Options:
|
||||
--headless run the signer with no window; anything not already allowed
|
||||
with \"Allow always\" is denied, so pre-approve in the GUI first
|
||||
--pair <uri> pair with a client from its nostrconnect:// URI, then run
|
||||
headless
|
||||
--version, -V print the version and exit
|
||||
--help, -h print this help and exit
|
||||
|
||||
With no options, Regent opens its window.";
|
||||
|
||||
fn main() -> glib::ExitCode {
|
||||
// Answered before the application is built so it works without a display.
|
||||
if std::env::args().skip(1).any(|arg| arg == "--version" || arg == "-V") {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
|
||||
// Answered before anything else so it works without a display.
|
||||
if args.iter().any(|arg| arg == "--version" || arg == "-V") {
|
||||
println!("{APP_ID} {VERSION}");
|
||||
return glib::ExitCode::SUCCESS;
|
||||
}
|
||||
if args.iter().any(|arg| arg == "--help" || arg == "-h") {
|
||||
println!("{USAGE}");
|
||||
return glib::ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
let (headless, pair) = match parse_args(&args) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
eprintln!("regent: {error}");
|
||||
eprintln!("{USAGE}");
|
||||
return glib::ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
if headless || pair.is_some() {
|
||||
return headless::run(pair);
|
||||
}
|
||||
|
||||
register_resources();
|
||||
application::run()
|
||||
}
|
||||
|
||||
/// Parse the (few) arguments we accept: `--headless` and `--pair <uri>`.
|
||||
fn parse_args(args: &[String]) -> Result<(bool, Option<String>), String> {
|
||||
let mut headless = false;
|
||||
let mut pair = 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);
|
||||
}
|
||||
_ => match arg.strip_prefix("--pair=") {
|
||||
Some(value) => pair = Some(value.to_string()),
|
||||
None => return Err(format!("unknown argument: {arg}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok((headless, pair))
|
||||
}
|
||||
|
||||
/// Directories that may hold an installed copy of the GResource, in the order
|
||||
/// the XDG base directory specification gives them: the user's data home first
|
||||
/// (`~/.local/share`, where a `meson install --prefix=$HOME/.local` lands),
|
||||
|
||||
@@ -25,6 +25,15 @@ where
|
||||
runtime().spawn(future);
|
||||
}
|
||||
|
||||
/// Run `future` to completion on the async runtime, blocking the caller.
|
||||
///
|
||||
/// This is the headless entry point, where there is no GTK main loop to
|
||||
/// marshal results back to: the future owns the whole flow and returns its own
|
||||
/// result.
|
||||
pub fn block_on<F: Future>(future: F) -> F::Output {
|
||||
runtime().block_on(future)
|
||||
}
|
||||
|
||||
/// Run `future` on the async runtime and hand the result to `then` on the main
|
||||
/// loop. Errors arrive stringified — they only ever end up in a dialog.
|
||||
///
|
||||
|
||||
+279
-14
@@ -38,6 +38,10 @@ pub struct SignerConfig {
|
||||
pub secret: String,
|
||||
/// Asks the user before any sensitive request is answered.
|
||||
pub approver: Approver,
|
||||
/// Relays a client asked us to use (`nostrconnect://`), on top of the
|
||||
/// configured ones. Used for subscriptions and publishing only — never
|
||||
/// advertised in the bunker URI or in `get_relays`.
|
||||
pub extra_relays: Vec<String>,
|
||||
/// Which applications have been approved, and what they may do silently.
|
||||
pub registry: Arc<Mutex<AppRegistry>>,
|
||||
/// Caps silent answers for each stored "always" permission.
|
||||
@@ -67,6 +71,7 @@ impl SignerConfig {
|
||||
relays,
|
||||
secret: random_secret(),
|
||||
approver,
|
||||
extra_relays: Vec::new(),
|
||||
registry,
|
||||
rate: RateLimiter::new(auto_approve_limit),
|
||||
activity,
|
||||
@@ -86,13 +91,21 @@ pub struct Signer {
|
||||
config: Arc<SignerConfig>,
|
||||
client: Client,
|
||||
running: Arc<AtomicBool>,
|
||||
/// Configured relays plus any the client asked for: where we listen and
|
||||
/// answer, as opposed to the advertised list in `config.relays`.
|
||||
relay_count: usize,
|
||||
uri: String,
|
||||
}
|
||||
|
||||
impl Signer {
|
||||
pub async fn start(config: SignerConfig) -> Result<Self> {
|
||||
let config = Arc::new(config);
|
||||
let urls = config.relay_urls()?;
|
||||
let mut urls = config.relay_urls()?;
|
||||
for relay in &config.extra_relays {
|
||||
urls.push(RelayUrl::parse(relay)?);
|
||||
}
|
||||
urls.sort();
|
||||
urls.dedup();
|
||||
|
||||
let client = Client::new();
|
||||
for url in &urls {
|
||||
@@ -175,6 +188,7 @@ impl Signer {
|
||||
config,
|
||||
client,
|
||||
running,
|
||||
relay_count: urls.len(),
|
||||
uri,
|
||||
})
|
||||
}
|
||||
@@ -188,14 +202,153 @@ impl Signer {
|
||||
self.config.device_keys.public_key()
|
||||
}
|
||||
|
||||
pub fn relays(&self) -> &[String] {
|
||||
&self.config.relays
|
||||
/// How many relays we actually listen on: the configured ones plus any the
|
||||
/// paired client asked us to use. The advertised list is `config.relays`.
|
||||
pub fn relay_count(&self) -> usize {
|
||||
self.relay_count
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.running.store(false, Ordering::SeqCst);
|
||||
self.client.disconnect().await;
|
||||
}
|
||||
|
||||
/// Finish a client-initiated pairing: send the `connect` response carrying
|
||||
/// the client's secret to the client's own relays.
|
||||
///
|
||||
/// Registering the client is the caller's decision; this is only the
|
||||
/// transport half. It fails loudly if no relay accepted the response —
|
||||
/// otherwise the client waits forever for a secret that never arrives.
|
||||
pub async fn complete_pairing(&self, pairing: &ClientPairing) -> Result<()> {
|
||||
let event = connect_response(&self.config.device_keys, &pairing.client, &pairing.secret)?;
|
||||
let output = self
|
||||
.client
|
||||
.send_event(&event)
|
||||
.to(pairing.relays.clone())
|
||||
.await?;
|
||||
if output.success.is_empty() {
|
||||
let detail = output
|
||||
.failed
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
return Err(format!(
|
||||
"none of the client's relays accepted the connect response ({detail})"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A client-initiated pairing, parsed from a `nostrconnect://` URI.
|
||||
///
|
||||
/// Everything but `client`, `relays` and `secret` is client-supplied display
|
||||
/// information.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClientPairing {
|
||||
pub client: PublicKey,
|
||||
pub relays: Vec<RelayUrl>,
|
||||
pub secret: String,
|
||||
pub name: Option<String>,
|
||||
pub url: Option<String>,
|
||||
pub image: Option<String>,
|
||||
/// The `perms` the client asked for, if any, as the raw string.
|
||||
pub requested: Option<String>,
|
||||
}
|
||||
|
||||
impl ClientPairing {
|
||||
pub fn client_info(&self) -> ClientInfo {
|
||||
ClientInfo {
|
||||
public_key: self.client,
|
||||
name: self.name.clone(),
|
||||
url: self.url.clone(),
|
||||
image: self.image.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a spec-shaped `nostrconnect://` URI (the client-initiated flow).
|
||||
///
|
||||
/// Parsed by hand, **not** with `NostrConnectUri::parse`: that one expects a
|
||||
/// non-standard `metadata=<json>` query parameter, while NIP-46 clients send
|
||||
/// `name`/`url`/`image`/`perms`. The bunker direction still uses rust-nostr.
|
||||
pub fn parse_client_uri(uri: &str) -> Result<ClientPairing> {
|
||||
let parsed = url::Url::parse(uri)?;
|
||||
if parsed.scheme() == "bunker" {
|
||||
return Err("expected a nostrconnect:// URI (a bunker:// one is for the client)".into());
|
||||
}
|
||||
if parsed.scheme() != "nostrconnect" {
|
||||
return Err(format!("unsupported URI scheme: {}", parsed.scheme()).into());
|
||||
}
|
||||
|
||||
let client = PublicKey::from_hex(parsed.host_str().unwrap_or_default())?;
|
||||
|
||||
let mut relays = Vec::new();
|
||||
let mut secret = None;
|
||||
let mut name = None;
|
||||
let mut url = None;
|
||||
let mut image = None;
|
||||
let mut requested = None;
|
||||
for (key, value) in parsed.query_pairs() {
|
||||
match key.as_ref() {
|
||||
"relay" => relays.push(RelayUrl::parse(value.as_ref())?),
|
||||
"secret" => secret = Some(value.to_string()),
|
||||
"name" => name = Some(value.to_string()),
|
||||
"url" => url = Some(value.to_string()),
|
||||
"image" => image = Some(value.to_string()),
|
||||
"perms" => requested = Some(value.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(secret) = secret.filter(|secret| !secret.is_empty()) else {
|
||||
return Err("the nostrconnect:// URI has no secret".into());
|
||||
};
|
||||
if relays.is_empty() {
|
||||
return Err("the nostrconnect:// URI has no relay".into());
|
||||
}
|
||||
|
||||
Ok(ClientPairing {
|
||||
client,
|
||||
relays,
|
||||
secret,
|
||||
// Bound client-supplied text: it reaches a dialog, the log and apps.json.
|
||||
name: name
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.map(|name| bound(&name, 64)),
|
||||
url: url.map(|url| bound(&url, 256)),
|
||||
image: image.map(|image| bound(&image, 256)),
|
||||
requested: requested.map(|perms| bound(&perms, 200)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Trim client-supplied text to a sane length.
|
||||
fn bound(value: &str, limit: usize) -> String {
|
||||
value.chars().take(limit).collect()
|
||||
}
|
||||
|
||||
/// The event a client-initiated pairing expects back: the client's secret as
|
||||
/// the `result`, p-tagging the client and signed by the **device** key (the
|
||||
/// client learns the remote-signer pubkey from this event's author).
|
||||
fn connect_response(device_keys: &Keys, client: &PublicKey, secret: &str) -> Result<Event> {
|
||||
let payload = serde_json::json!({ "id": random_id(), "result": secret }).to_string();
|
||||
let content = nip44::encrypt(device_keys.secret_key(), client, payload, nip44::Version::V2)?;
|
||||
let unsigned = UnsignedEvent::new(
|
||||
device_keys.public_key(),
|
||||
Timestamp::now(),
|
||||
Kind::NostrConnect,
|
||||
[Tag::public_key(*client)],
|
||||
content,
|
||||
);
|
||||
Ok(device_keys.sign_event(unsigned)?)
|
||||
}
|
||||
|
||||
/// A short random request id. The client-initiated flow has no request to match
|
||||
/// against, so the id only has to be present.
|
||||
fn random_id() -> String {
|
||||
Keys::generate().public_key().to_hex()[..16].to_string()
|
||||
}
|
||||
|
||||
/// Build a `bunker://` URI: device pubkey, relays, and the pairing secret.
|
||||
@@ -280,10 +433,14 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
let result: std::result::Result<String, String> = match method {
|
||||
"connect" => {
|
||||
let presented = params.get(1).cloned().unwrap_or_default();
|
||||
if presented != config.secret {
|
||||
Err("unauthorized".to_string())
|
||||
} else if approved {
|
||||
// An approved client is trusted even without the pairing secret: the
|
||||
// bunker flow proved it once, and a client-initiated pairing proved
|
||||
// key possession by receiving our response on its own pubkey. A new
|
||||
// client must still present the secret.
|
||||
if approved {
|
||||
Ok("ack".to_string())
|
||||
} else if presented != config.secret {
|
||||
Err("unauthorized".to_string())
|
||||
} else {
|
||||
let requested = requested_perms(¶ms);
|
||||
match config
|
||||
@@ -495,7 +652,7 @@ fn record(
|
||||
outcome: &str,
|
||||
) {
|
||||
config.activity.record(&Entry {
|
||||
at: now_secs(),
|
||||
at: audit::now(),
|
||||
app: client.public_key.to_hex(),
|
||||
name: client.name.clone(),
|
||||
method: method.to_string(),
|
||||
@@ -505,13 +662,6 @@ fn record(
|
||||
let _ = config.changes.try_send(());
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|since| since.as_secs() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A client with no recorded metadata, for an approved key we cannot describe.
|
||||
fn bare_client(public_key: &PublicKey) -> ClientInfo {
|
||||
ClientInfo {
|
||||
@@ -851,6 +1001,7 @@ mod tests {
|
||||
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,
|
||||
@@ -1447,6 +1598,120 @@ mod tests {
|
||||
assert_eq!(policy["methods"], serde_json::json!([]));
|
||||
}
|
||||
|
||||
/// A spec-shaped `nostrconnect://` URI parses without rust-nostr's
|
||||
/// non-standard `metadata=` parameter.
|
||||
#[test]
|
||||
fn a_nostrconnect_uri_is_parsed() {
|
||||
let client = Keys::generate();
|
||||
let uri = format!(
|
||||
"nostrconnect://{}?relay=wss%3A%2F%2Frelay.example.com&secret=s3cret\
|
||||
&name=My+App&url=https%3A%2F%2Fexample.com%2Fapp\
|
||||
&image=https%3A%2F%2Fexample.com%2Fi.png&perms=sign_event%3A1",
|
||||
client.public_key().to_hex()
|
||||
);
|
||||
|
||||
let pairing = parse_client_uri(&uri).expect("parse");
|
||||
assert_eq!(pairing.client, client.public_key());
|
||||
assert_eq!(pairing.secret, "s3cret");
|
||||
assert_eq!(pairing.name.as_deref(), Some("My App"));
|
||||
assert_eq!(pairing.url.as_deref(), Some("https://example.com/app"));
|
||||
assert_eq!(pairing.image.as_deref(), Some("https://example.com/i.png"));
|
||||
assert_eq!(pairing.requested.as_deref(), Some("sign_event:1"));
|
||||
assert_eq!(pairing.relays.len(), 1);
|
||||
assert!(pairing.relays[0].to_string().starts_with("wss://relay.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_incomplete_or_bunker_uri_is_refused() {
|
||||
let keys = Keys::generate();
|
||||
let bunker = bunker_uri(&keys.public_key(), &["wss://relay.example.com".to_string()], "abc");
|
||||
assert!(parse_client_uri(&bunker).is_err(), "bunker:// is the other direction");
|
||||
|
||||
let no_secret = format!(
|
||||
"nostrconnect://{}?relay=wss%3A%2F%2Frelay.example.com",
|
||||
keys.public_key().to_hex()
|
||||
);
|
||||
assert!(parse_client_uri(&no_secret).is_err());
|
||||
|
||||
let no_relay = format!("nostrconnect://{}?secret=abc", keys.public_key().to_hex());
|
||||
assert!(parse_client_uri(&no_relay).is_err());
|
||||
|
||||
assert!(parse_client_uri("https://example.com").is_err());
|
||||
}
|
||||
|
||||
/// The client learns the signer key from the response author and must get
|
||||
/// its own secret back as the result.
|
||||
#[test]
|
||||
fn the_connect_response_carries_the_secret() {
|
||||
let device = Keys::generate();
|
||||
let client = Keys::generate();
|
||||
let event = connect_response(&device, &client.public_key(), "s3cret").expect("build");
|
||||
|
||||
assert_eq!(event.kind, Kind::NostrConnect);
|
||||
assert_eq!(event.pubkey, device.public_key());
|
||||
let hex = client.public_key().to_hex();
|
||||
assert!(
|
||||
event
|
||||
.tags
|
||||
.iter()
|
||||
.any(|tag| tag.kind() == "p" && tag.content() == Some(hex.as_str())),
|
||||
"the response must p-tag the client"
|
||||
);
|
||||
|
||||
let plain = nip44::decrypt(client.secret_key(), &device.public_key(), &event.content)
|
||||
.expect("the client decrypts it");
|
||||
let value: serde_json::Value = serde_json::from_str(&plain).unwrap();
|
||||
assert_eq!(value["result"].as_str(), Some("s3cret"));
|
||||
}
|
||||
|
||||
/// An approved client may reconnect without the pairing secret (the
|
||||
/// client-initiated flow proves key possession instead).
|
||||
#[tokio::test]
|
||||
async fn an_approved_client_reconnects_without_the_secret() {
|
||||
let client = Keys::generate();
|
||||
let (approver, task, _) = recording_approver(|_| Decision::Always);
|
||||
let config = config("ws://127.0.0.1:1", approver);
|
||||
let device = pair(&client, &config).await;
|
||||
|
||||
let request = client_request(
|
||||
&client,
|
||||
&device,
|
||||
"connect",
|
||||
serde_json::json!(["", "not-the-secret", "", ""]),
|
||||
);
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
task.abort();
|
||||
|
||||
assert!(read_response(&response, &client, &device)["result"].is_string());
|
||||
}
|
||||
|
||||
/// A new client still has to prove it was handed the connection string.
|
||||
#[tokio::test]
|
||||
async fn an_unapproved_client_needs_the_secret() {
|
||||
let client = Keys::generate();
|
||||
let (approver, task, _) = recording_approver(|_| Decision::Always);
|
||||
let config = config("ws://127.0.0.1:1", approver);
|
||||
let device = config.device_keys.public_key();
|
||||
|
||||
let request = client_request(
|
||||
&client,
|
||||
&device,
|
||||
"connect",
|
||||
serde_json::json!(["", "not-the-secret", "", ""]),
|
||||
);
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
let answer = read_response(&response, &client, &device);
|
||||
task.abort();
|
||||
|
||||
assert!(answer["error"].is_string(), "got {answer}");
|
||||
}
|
||||
|
||||
/// Registry changes wake the Apps and Activity pages.
|
||||
#[tokio::test]
|
||||
async fn registry_changes_are_announced() {
|
||||
|
||||
@@ -45,6 +45,14 @@ pub mod outcome {
|
||||
pub const LOGGED_OUT: &str = "logged-out";
|
||||
}
|
||||
|
||||
/// The current Unix time in seconds, for [`Entry::at`].
|
||||
pub fn now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|since| since.as_secs() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Records handled when the file grows without bound. Every line is bounded
|
||||
/// (client names are truncated, the rest is fixed-size), so 500 lines fit well
|
||||
/// under this.
|
||||
|
||||
@@ -266,14 +266,14 @@ fn show_running(handles: &Handles, signer: &Signer) {
|
||||
// Deliberately logs the public key and relay count, never the secret.
|
||||
eprintln!(
|
||||
"regent: signer listening on {} relay(s) as {}",
|
||||
signer.relays().len(),
|
||||
signer.relay_count(),
|
||||
signer.device_public_key().to_bech32().unwrap_or_default()
|
||||
);
|
||||
|
||||
handles.stack.set_visible_child_name("ready");
|
||||
handles
|
||||
.status
|
||||
.set_subtitle(&format!("Running on {} relay(s)", signer.relays().len()));
|
||||
.set_subtitle(&format!("Running on {} relay(s)", signer.relay_count()));
|
||||
handles.uri.set_subtitle(signer.bunker_uri());
|
||||
handles
|
||||
.device
|
||||
|
||||
Reference in new issue
Block a user