Remember per-app permissions and rate-limit silent answers

This commit is contained in:
raucao committed 2026-11-13 16:38:26 +04:00
1 parent f1803d130d
commit ddf15b3a1f
5 files changed
+164

No files matched your search

@@ -11,6 +11,11 @@
<summary>Window height</summary>
<description>Height of the main window, in pixels.</description>
</key>
<key name="auto-approve-limit" type="i">
<default>30</default>
<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="relays" type="as">
<default>['wss://nostr.kosmos.org']</default>
<summary>Relays</summary>
+1
View File
@@ -28,6 +28,7 @@ cargo_build = custom_target(binary_name,
'src/runtime.rs',
'src/signer/approval.rs',
'src/signer/mod.rs',
'src/signer/policy.rs',
'src/state.rs',
'src/store/apps.rs',
'src/store/mod.rs',
+6
View File
@@ -25,6 +25,12 @@ impl Config {
self.settings.int("window-height")
}
/// How many requests per minute a stored "always" permission may answer
/// silently, per application, before Regent asks again.
pub fn auto_approve_limit(&self) -> u32 {
self.settings.int("auto-approve-limit").max(0) as u32
}
/// 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> {
+72
View File
@@ -0,0 +1,72 @@
//! Deciding whether a request may be answered without asking.
//!
//! The persistence lives in [`crate::store::apps`]: an "always" answer stores a
//! per-application [`Permission`]. This module only owns the runtime guard
//! around those stored permissions — a rate limit, so that a stored policy
//! cannot turn into an unbounded silent stream.
//!
//! [`Permission`]: crate::store::apps::Permission
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// The window over which auto-approvals are counted.
pub const WINDOW: Duration = Duration::from_secs(60);
/// Caps how many requests a stored "always" permission answers silently, per
/// application. Past the cap Regent asks again, so a runaway or compromised
/// client turns back into prompts instead of an open tap.
pub struct RateLimiter {
limit: u32,
recent: Mutex<HashMap<String, VecDeque<Instant>>>,
}
impl RateLimiter {
pub fn new(limit: u32) -> Self {
Self {
limit,
recent: Mutex::new(HashMap::new()),
}
}
/// Reserve one silent answer for `app`, if the count over the last
/// [`WINDOW`] is still under the limit. `false` means the request must be
/// put to the user after all.
pub fn claim(&self, app: &str) -> bool {
let now = Instant::now();
let mut recent = self.recent.lock().unwrap();
let answers = recent.entry(app.to_string()).or_default();
while answers
.front()
.is_some_and(|at| now.duration_since(*at) > WINDOW)
{
answers.pop_front();
}
if answers.len() as u32 >= self.limit {
return false;
}
answers.push_back(now);
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_rate_limit_is_per_application() {
let limiter = RateLimiter::new(2);
assert!(limiter.claim("a"));
assert!(limiter.claim("a"));
assert!(!limiter.claim("a"), "the third answer is over the cap");
assert!(limiter.claim("b"), "another application has its own budget");
}
#[test]
fn a_limit_of_zero_never_auto_approves() {
let limiter = RateLimiter::new(0);
assert!(!limiter.claim("a"));
}
}
+80
View File
@@ -3,6 +3,7 @@
//! Not secret, so it is a plain JSON file under the config directory — unlike
//! the keys, which live in the keyring.
use std::collections::BTreeSet;
use std::path::PathBuf;
use nostr::prelude::*;
@@ -14,6 +15,30 @@ use crate::APP_ID;
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
pub type Result<T> = std::result::Result<T, Error>;
/// One thing an application was told it may do without asking again.
///
/// This is what an "always" answer in a dialog turns into. It is deliberately
/// coarse: a method name for encryption, a single kind for signing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Permission {
/// Sign events of this kind.
Kind(u16),
/// Encrypt with this NIP method (`nip04_encrypt` / `nip44_encrypt`).
/// Decryption is never stored: it always asks.
Method(String),
}
/// What an application may do without being asked.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Policy {
/// NIP method names approved wholesale.
#[serde(default)]
pub methods: BTreeSet<String>,
/// Event kinds approved for `sign_event`.
#[serde(default)]
pub kinds: BTreeSet<u16>,
}
/// An application that may ask this signer for things.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct App {
@@ -28,6 +53,10 @@ pub struct App {
pub image: Option<String>,
/// Unix timestamp of when it was approved.
pub approved_at: i64,
/// Requests it may answer without asking. Empty until the user picks
/// "Always"; older registries simply deserialize to the default.
#[serde(default)]
pub policy: Policy,
}
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -68,9 +97,59 @@ impl AppRegistry {
self.apps.iter().any(|app| app.public_key == hex)
}
/// The display hints recorded for an approved application.
pub fn client(&self, public_key: &PublicKey) -> Option<ClientInfo> {
let hex = public_key.to_hex();
self.apps
.iter()
.find(|app| app.public_key == hex)
.map(|app| ClientInfo {
public_key: *public_key,
name: app.name.clone(),
url: app.url.clone(),
image: app.image.clone(),
})
}
/// Whether a stored permission covers this request.
pub fn permits(&self, public_key: &PublicKey, permission: &Permission) -> bool {
let hex = public_key.to_hex();
let Some(app) = self.apps.iter().find(|app| app.public_key == hex) else {
return false;
};
match permission {
Permission::Kind(kind) => app.policy.kinds.contains(kind),
Permission::Method(method) => app.policy.methods.contains(method),
}
}
/// Remember an "always" answer. Unknown applications are ignored: there is
/// nothing to remember against.
pub fn allow(&mut self, public_key: &PublicKey, permission: Permission) -> Result<()> {
let hex = public_key.to_hex();
let Some(app) = self.apps.iter_mut().find(|app| app.public_key == hex) else {
return Ok(());
};
match permission {
Permission::Kind(kind) => {
app.policy.kinds.insert(kind);
}
Permission::Method(method) => {
app.policy.methods.insert(method);
}
}
self.save()
}
/// Record an approval. Metadata is whatever the client declared.
pub fn approve(&mut self, client: &ClientInfo) -> Result<()> {
let public_key = client.public_key.to_hex();
let policy = self
.apps
.iter()
.find(|app| app.public_key == public_key)
.map(|app| app.policy.clone())
.unwrap_or_default();
self.apps.retain(|app| app.public_key != public_key);
self.apps.push(App {
public_key,
@@ -81,6 +160,7 @@ impl AppRegistry {
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_secs() as i64)
.unwrap_or_default(),
policy,
});
self.save()
}