Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ once_cell = "1.20.2"
bitcoin = "0.32.5"
dialoguer = "0.11"
dirs = "6.0.0"
dotenvy = "0.15.7"
clearscreen = "4.0.1"
tonic = "0.14.2"
prost = "0.14.1"
Expand Down
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,8 @@ payment_retries_interval = 60 # seconds between retries
#### Nostr Configuration
```toml
[nostr]
# Your Mostro daemon's private key (nsec format)
# Your Mostro daemon's private key (nsec format). Optional if MOSTRO_NSEC_PRIVKEY
# is set via environment variable or ~/.mostro/.env (see below).
nsec_privkey = 'nsec1...'

# Relays to connect to
Expand All @@ -511,6 +512,37 @@ rana --vanity mostro

**Important**: Never reuse keys between Mostro instances. Each daemon needs a unique identity.

##### Providing the nsec via environment variable

For better separation of secrets from config, Mostro can read the nsec from the
`MOSTRO_NSEC_PRIVKEY` environment variable. When set, it takes precedence over
`nsec_privkey` in `settings.toml`.

Three common ways to provide it:

1. **`~/.mostro/.env`** (auto-loaded at startup, `chmod 600` recommended):
```
MOSTRO_NSEC_PRIVKEY=nsec1...
```
Comment on lines +523 to +526
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add a language specifier to the new fenced code block (MD040).

The .env example opens with a bare triple-backtick, which violates markdownlint MD040 (also flagged by static analysis on line 524).

📝 Proposed fix
 1. **`~/.mostro/.env`** (auto-loaded at startup, `chmod 600` recommended):
-   ```
+   ```ini
    MOSTRO_NSEC_PRIVKEY=nsec1...
    ```

As per coding guidelines: "Add a language specifier to every fenced code block in documentation to comply with markdownlint MD040".

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 524-524: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.md` around lines 523 - 526, The fenced code block in README.md showing
the MOSTRO_NSEC_PRIVKEY example is missing a language specifier and triggers
markdownlint MD040; update the triple-backtick that opens the block to include a
language (e.g., "ini") so the block becomes ```ini and thus documents syntax and
satisfies MD040—look for the snippet containing MOSTRO_NSEC_PRIVKEY and change
the opening fence accordingly.

The interactive setup wizard can create this file for you.

2. **systemd service**:
```ini
[Service]
Environment="MOSTRO_NSEC_PRIVKEY=nsec1..."
# or, better, with LoadCredential and a credential file:
# LoadCredential=mostro_nsec:/etc/mostro/nsec
```

3. **Docker**:
```bash
docker run -e MOSTRO_NSEC_PRIVKEY=nsec1... mostro
# or via Docker secrets / compose env_file
```

Precedence is: real env var > `~/.mostro/.env` > `settings.toml`. Leaving
`nsec_privkey` in `settings.toml` is still supported for existing installations.

---

#### Mostro Business Logic
Expand Down
10 changes: 8 additions & 2 deletions docs/STARTUP_AND_CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,14 @@ Configuration is loaded from `~/.mostro/settings.toml` (template: `settings.tpl.
- Example (absolute path; use a real path — **do not** use `~`; SQLx does not expand tilde): `"sqlite:///home/youruser/.mostro/mostro.db"`
- Default: `"sqlite://mostro.db"`

**Nostr** (`src/config/types.rs:47-54`):
- `nsec_privkey` (String): Mostro's Nostr private key in nsec format
**Nostr** (`src/config/types.rs`):
- `nsec_privkey` (String): Mostro's Nostr private key in nsec format.
- Can be overridden by the `MOSTRO_NSEC_PRIVKEY` environment variable
(env var takes precedence; whitespace-only values are ignored).
- Mostro also auto-loads `<settings_dir>/.env` at startup (e.g.
`~/.mostro/.env`) so the variable can live in a separate file with
restricted permissions.
- Precedence: real env var > `<settings_dir>/.env` > `settings.toml`.
- `relays` (Vec<String>): List of Nostr relay URLs for event broadcasting
- Default: `['ws://localhost:7000']`
- Note: At least one relay required
Expand Down
4 changes: 3 additions & 1 deletion src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ pub struct LightningSettings {
/// Nostr configuration settings
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct NostrSettings {
/// Nostr private key
/// Nostr private key. Optional when `MOSTRO_NSEC_PRIVKEY` is provided via
/// environment variable or `<settings_dir>/.env`.
#[serde(default)]
pub nsec_privkey: String,
/// Nostr relays list
pub relays: Vec<String>,
Expand Down
161 changes: 160 additions & 1 deletion src/config/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,30 @@ use std::io::IsTerminal;
use std::path::PathBuf;

const DB_FILENAME: &str = "mostro.db";
const ENV_FILENAME: &str = ".env";
const NSEC_ENV_VAR: &str = "MOSTRO_NSEC_PRIVKEY";

/// Loads the optional `<settings_dir>/.env` file so that values placed there
/// become available through `std::env::var`. Variables already set in the
/// process environment take precedence and are never overwritten.
fn load_env_file(settings_dir: &std::path::Path) {
let env_file = settings_dir.join(ENV_FILENAME);
if env_file.exists() {
let _ = dotenvy::from_path(&env_file);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report .env parsing/loading failures

This ignores any error from dotenvy::from_path, so malformed or unreadable .env files fail silently. In deployments that rely on MOSTRO_NSEC_PRIVKEY from .env, startup can then proceed with the TOML value (or an empty key) and either use the wrong identity or fail later with an unrelated parse error, making the root cause hard to diagnose. Propagating or logging this error would prevent silent misconfiguration.

Useful? React with 👍 / 👎.

}
}

/// If the `MOSTRO_NSEC_PRIVKEY` environment variable is set to a non-empty
/// value, override the nsec loaded from `settings.toml`. Whitespace is
/// trimmed; blank values are ignored so the TOML stays the fallback.
fn apply_nsec_env_override(settings: &mut Settings) {
if let Ok(nsec_from_env) = std::env::var(NSEC_ENV_VAR) {
let trimmed = nsec_from_env.trim();
if !trimmed.is_empty() {
settings.nostr.nsec_privkey = trimmed.to_string();
}
}
}

/// Validates Mostro settings on startup
fn validate_mostro_settings(settings: &Settings) -> Result<(), MostroError> {
Expand Down Expand Up @@ -56,10 +80,15 @@ pub fn init_configuration_file(config_path: Option<String>) -> Result<(), Mostro
std::fs::create_dir_all(&settings_dir)
.map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?;
}

// Load `<settings_dir>/.env` so MOSTRO_NSEC_PRIVKEY (and any future env
// overrides) can be read from it. Real env vars keep precedence.
load_env_file(&settings_dir);

let config_file_path = settings_dir.join("settings.toml");

if !config_file_path.exists() {
let settings = if std::io::stdin().is_terminal() {
let mut settings = if std::io::stdin().is_terminal() {
// Interactive: show setup menu (wizard or manual template)
wizard::run_setup_menu(&settings_dir, &config_file_path)?
} else {
Expand All @@ -73,6 +102,7 @@ pub fn init_configuration_file(config_path: Option<String>) -> Result<(), Mostro
std::process::exit(0);
};

apply_nsec_env_override(&mut settings);
validate_mostro_settings(&settings)?;
init_mostro_settings(settings);
tracing::info!("Settings correctly loaded!");
Expand All @@ -87,6 +117,10 @@ pub fn init_configuration_file(config_path: Option<String>) -> Result<(), Mostro
let mut settings: Settings = toml::from_str(&contents)
.map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?;

// Apply MOSTRO_NSEC_PRIVKEY override before validation so an empty TOML
// value is fine when the env var is set.
apply_nsec_env_override(&mut settings);

// Validate settings before initializing
validate_mostro_settings(&settings)?;

Expand All @@ -100,3 +134,128 @@ pub fn init_configuration_file(config_path: Option<String>) -> Result<(), Mostro

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use crate::config::types::{
DatabaseSettings, LightningSettings, MostroSettings, NostrSettings, RpcSettings,
};
use std::sync::Mutex;

// Tests that read/write MOSTRO_NSEC_PRIVKEY must run serially because the
// process environment is shared across threads.
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// RAII guard that saves the current value of an env var and restores it
/// on drop, so tests don't leak state into each other.
struct EnvVarGuard {
key: &'static str,
previous: Option<String>,
}

impl EnvVarGuard {
fn new(key: &'static str) -> Self {
let previous = std::env::var(key).ok();
std::env::remove_var(key);
Self { key, previous }
}

fn set(&self, value: &str) {
std::env::set_var(self.key, value);
}
}

impl Drop for EnvVarGuard {
fn drop(&mut self) {
match &self.previous {
Some(val) => std::env::set_var(self.key, val),
None => std::env::remove_var(self.key),
}
}
}

fn make_settings(nsec: &str) -> Settings {
Settings {
database: DatabaseSettings::default(),
lightning: LightningSettings::default(),
nostr: NostrSettings {
nsec_privkey: nsec.to_string(),
relays: vec!["wss://relay.test".to_string()],
},
mostro: MostroSettings::default(),
rpc: RpcSettings::default(),
expiration: None,
}
}

#[test]
fn env_var_overrides_toml_nsec() {
let _lock = ENV_LOCK.lock().unwrap();
let guard = EnvVarGuard::new(NSEC_ENV_VAR);
guard.set("nsec_from_env");

let mut settings = make_settings("nsec_from_toml");
apply_nsec_env_override(&mut settings);

assert_eq!(settings.nostr.nsec_privkey, "nsec_from_env");
}

#[test]
fn empty_env_var_falls_back_to_toml() {
let _lock = ENV_LOCK.lock().unwrap();
let guard = EnvVarGuard::new(NSEC_ENV_VAR);
guard.set("");

let mut settings = make_settings("nsec_from_toml");
apply_nsec_env_override(&mut settings);

assert_eq!(settings.nostr.nsec_privkey, "nsec_from_toml");
}

#[test]
fn no_env_var_keeps_toml() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = EnvVarGuard::new(NSEC_ENV_VAR);

let mut settings = make_settings("nsec_from_toml");
apply_nsec_env_override(&mut settings);

assert_eq!(settings.nostr.nsec_privkey, "nsec_from_toml");
}

#[test]
fn whitespace_only_env_is_ignored() {
let _lock = ENV_LOCK.lock().unwrap();
let guard = EnvVarGuard::new(NSEC_ENV_VAR);
guard.set(" \t ");

let mut settings = make_settings("nsec_from_toml");
apply_nsec_env_override(&mut settings);

assert_eq!(settings.nostr.nsec_privkey, "nsec_from_toml");
}

#[test]
fn env_var_value_is_trimmed() {
let _lock = ENV_LOCK.lock().unwrap();
let guard = EnvVarGuard::new(NSEC_ENV_VAR);
guard.set(" nsec_from_env ");

let mut settings = make_settings("nsec_from_toml");
apply_nsec_env_override(&mut settings);

assert_eq!(settings.nostr.nsec_privkey, "nsec_from_env");
}

#[test]
fn toml_parses_without_nsec_privkey_field() {
// Operators who rely exclusively on MOSTRO_NSEC_PRIVKEY should be able
// to omit nsec_privkey from settings.toml entirely.
let toml_without_nsec = r#"relays = ["wss://relay.test"]"#;
let nostr: NostrSettings =
toml::from_str(toml_without_nsec).expect("nsec_privkey should be optional in TOML");
assert_eq!(nostr.nsec_privkey, "");
assert_eq!(nostr.relays, vec!["wss://relay.test"]);
}
}
Loading