1use anyhow::{Context, Result, anyhow};
20use serde_json::Value;
21use std::collections::HashMap;
22use std::fs;
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use std::sync::{Arc, Mutex, OnceLock};
26
27pub fn config_dir() -> Result<PathBuf> {
32 if let Ok(home) = std::env::var("WIRE_HOME") {
33 return Ok(PathBuf::from(home).join("config").join("wire"));
34 }
35 dirs::config_dir()
36 .map(|d| d.join("wire"))
37 .ok_or_else(|| anyhow!("could not resolve XDG_CONFIG_HOME — set WIRE_HOME"))
38}
39
40pub fn state_dir() -> Result<PathBuf> {
44 if let Ok(home) = std::env::var("WIRE_HOME") {
45 return Ok(PathBuf::from(home).join("state").join("wire"));
46 }
47 dirs::state_dir()
48 .or_else(dirs::data_local_dir)
49 .map(|d| d.join("wire"))
50 .ok_or_else(|| anyhow!("could not resolve XDG_STATE_HOME — set WIRE_HOME"))
51}
52
53pub fn private_key_path() -> Result<PathBuf> {
54 Ok(config_dir()?.join("private.key"))
55}
56pub fn agent_card_path() -> Result<PathBuf> {
57 Ok(config_dir()?.join("agent-card.json"))
58}
59pub fn trust_path() -> Result<PathBuf> {
60 Ok(config_dir()?.join("trust.json"))
61}
62pub fn config_toml_path() -> Result<PathBuf> {
63 Ok(config_dir()?.join("config.toml"))
64}
65pub fn inbox_dir() -> Result<PathBuf> {
66 Ok(state_dir()?.join("inbox"))
67}
68pub fn outbox_dir() -> Result<PathBuf> {
69 Ok(state_dir()?.join("outbox"))
70}
71
72static OUTBOX_LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
84
85fn outbox_lock(path: &Path) -> Arc<Mutex<()>> {
86 let registry = OUTBOX_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
87 let mut g = registry.lock().expect("OUTBOX_LOCKS poisoned");
88 g.entry(path.to_path_buf())
89 .or_insert_with(|| Arc::new(Mutex::new(())))
90 .clone()
91}
92
93pub fn append_outbox_record(peer: &str, record_bytes: &[u8]) -> Result<PathBuf> {
110 ensure_dirs()?;
111 let normalized = crate::agent_card::bare_handle(peer);
112 let path = outbox_dir()?.join(format!("{normalized}.jsonl"));
113 let lock = outbox_lock(&path);
114 let _g = lock.lock().expect("outbox per-path mutex poisoned");
115 let mut f = fs::OpenOptions::new()
116 .create(true)
117 .append(true)
118 .open(&path)
119 .with_context(|| format!("opening outbox {path:?}"))?;
120 let mut buf = Vec::with_capacity(record_bytes.len() + 1);
121 buf.extend_from_slice(record_bytes);
122 buf.push(b'\n');
123 f.write_all(&buf)
124 .with_context(|| format!("appending to {path:?}"))?;
125 Ok(path)
126}
127
128pub fn is_initialized() -> Result<bool> {
130 Ok(private_key_path()?.exists() && agent_card_path()?.exists())
131}
132
133pub fn ensure_dirs() -> Result<()> {
135 let cfg = config_dir()?;
136 fs::create_dir_all(&cfg).with_context(|| format!("creating {cfg:?}"))?;
137 fs::create_dir_all(state_dir()?)?;
138 fs::create_dir_all(inbox_dir()?)?;
139 fs::create_dir_all(outbox_dir()?)?;
140 set_dir_mode_0700(&cfg)?;
141 Ok(())
142}
143
144#[cfg(unix)]
145fn set_dir_mode_0700(path: &Path) -> Result<()> {
146 use std::os::unix::fs::PermissionsExt;
147 let mut perms = fs::metadata(path)?.permissions();
148 perms.set_mode(0o700);
149 fs::set_permissions(path, perms)?;
150 Ok(())
151}
152
153#[cfg(not(unix))]
154fn set_dir_mode_0700(_: &Path) -> Result<()> {
155 Ok(())
156}
157
158pub fn write_private_key(seed: &[u8; 32]) -> Result<()> {
160 let path = private_key_path()?;
161 fs::write(&path, seed).with_context(|| format!("writing {path:?}"))?;
162 set_file_mode_0600(&path)?;
163 Ok(())
164}
165
166#[cfg(unix)]
167fn set_file_mode_0600(path: &Path) -> Result<()> {
168 use std::os::unix::fs::PermissionsExt;
169 let mut perms = fs::metadata(path)?.permissions();
170 perms.set_mode(0o600);
171 fs::set_permissions(path, perms)?;
172 Ok(())
173}
174
175#[cfg(not(unix))]
176fn set_file_mode_0600(_: &Path) -> Result<()> {
177 Ok(())
178}
179
180pub fn read_private_key() -> Result<[u8; 32]> {
182 let path = private_key_path()?;
183 let bytes = fs::read(&path).with_context(|| format!("reading {path:?}"))?;
184 if bytes.len() != 32 {
185 return Err(anyhow!(
186 "private key file has wrong length ({} != 32)",
187 bytes.len()
188 ));
189 }
190 let mut seed = [0u8; 32];
191 seed.copy_from_slice(&bytes);
192 Ok(seed)
193}
194
195pub fn write_agent_card(card: &Value) -> Result<()> {
196 let path = agent_card_path()?;
197 let body = serde_json::to_vec_pretty(card)?;
198 let tmp = path.with_extension("json.tmp");
204 fs::write(&tmp, body).with_context(|| format!("writing tmp {tmp:?}"))?;
205 fs::rename(&tmp, &path).with_context(|| format!("atomic rename {tmp:?} → {path:?}"))?;
206 Ok(())
207}
208
209pub fn read_agent_card() -> Result<Value> {
210 let path = agent_card_path()?;
211 let body = fs::read(&path).with_context(|| format!("reading {path:?}"))?;
212 Ok(serde_json::from_slice(&body)?)
213}
214
215pub fn display_overrides_path() -> Result<PathBuf> {
223 Ok(config_dir()?.join("display.json"))
224}
225
226#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
227pub struct DisplayOverrides {
228 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub nickname: Option<String>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub emoji: Option<String>,
232}
233
234pub fn read_display_overrides() -> Result<DisplayOverrides> {
235 read_display_overrides_at(&display_overrides_path()?)
236}
237
238pub fn read_display_overrides_at(path: &Path) -> Result<DisplayOverrides> {
239 if !path.exists() {
240 return Ok(DisplayOverrides::default());
241 }
242 let body = fs::read(path).with_context(|| format!("reading {path:?}"))?;
243 Ok(serde_json::from_slice(&body)?)
244}
245
246pub fn write_display_overrides(overrides: &DisplayOverrides) -> Result<()> {
247 let path = display_overrides_path()?;
248 if let Some(parent) = path.parent() {
249 fs::create_dir_all(parent).with_context(|| format!("creating {parent:?}"))?;
250 }
251 let body = serde_json::to_vec_pretty(overrides)?;
252 let tmp = path.with_extension("json.tmp");
256 fs::write(&tmp, body).with_context(|| format!("writing tmp {tmp:?}"))?;
257 fs::rename(&tmp, &path).with_context(|| format!("atomic rename {tmp:?} → {path:?}"))?;
258 Ok(())
259}
260
261pub fn write_trust(trust: &Value) -> Result<()> {
262 let path = trust_path()?;
263 let body = serde_json::to_vec_pretty(trust)?;
264 fs::write(&path, body).with_context(|| format!("writing {path:?}"))?;
265 Ok(())
266}
267
268pub fn read_trust() -> Result<Value> {
269 let path = trust_path()?;
270 if !path.exists() {
271 return Ok(crate::trust::empty_trust());
272 }
273 let body = fs::read(&path).with_context(|| format!("reading {path:?}"))?;
274 Ok(serde_json::from_slice(&body)?)
275}
276
277pub fn relay_state_path() -> Result<PathBuf> {
282 Ok(config_dir()?.join("relay.json"))
283}
284
285pub fn read_relay_state() -> Result<Value> {
286 let path = relay_state_path()?;
287 if !path.exists() {
288 return Ok(serde_json::json!({"self": Value::Null, "peers": {}}));
289 }
290 let body = fs::read(&path).with_context(|| format!("reading {path:?}"))?;
291 Ok(serde_json::from_slice(&body)?)
292}
293
294pub fn write_relay_state(state: &Value) -> Result<()> {
295 let path = relay_state_path()?;
296 let body = serde_json::to_vec_pretty(state)?;
297 fs::write(&path, body).with_context(|| format!("writing {path:?}"))?;
298 set_file_mode_0600(&path)?;
299 Ok(())
300}
301
302fn relay_state_lock_path() -> Result<PathBuf> {
307 Ok(config_dir()?.join("relay.lock"))
308}
309
310pub fn update_relay_state<F>(modifier: F) -> Result<()>
325where
326 F: FnOnce(&mut Value) -> Result<()>,
327{
328 use fs2::FileExt;
329 let lock_path = relay_state_lock_path()?;
330 if let Some(parent) = lock_path.parent() {
331 fs::create_dir_all(parent).with_context(|| format!("creating {parent:?}"))?;
332 }
333 let lock_file = fs::OpenOptions::new()
336 .create(true)
337 .truncate(false)
338 .read(true)
339 .write(true)
340 .open(&lock_path)
341 .with_context(|| format!("opening {lock_path:?}"))?;
342 lock_file
343 .lock_exclusive()
344 .with_context(|| format!("flock {lock_path:?}"))?;
345
346 let mut state = read_relay_state()?;
349 let result = modifier(&mut state);
350 let write_result = if result.is_ok() {
351 write_relay_state(&state)
352 } else {
353 Ok(())
354 };
355 let _ = fs2::FileExt::unlock(&lock_file);
358 result?;
359 write_result?;
360 Ok(())
361}
362
363#[cfg(test)]
368pub(crate) mod test_support {
369 use std::sync::Mutex;
370
371 pub static ENV_LOCK: Mutex<()> = Mutex::new(());
372
373 pub fn with_temp_home<F: FnOnce()>(f: F) {
374 let _guard = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
376 let tmp = std::env::temp_dir().join(format!("wire-test-{}", rand::random::<u32>()));
377 unsafe { std::env::set_var("WIRE_HOME", &tmp) };
379 let _ = std::fs::remove_dir_all(&tmp);
380 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
381 unsafe { std::env::remove_var("WIRE_HOME") };
382 let _ = std::fs::remove_dir_all(&tmp);
383 if let Err(e) = result {
384 std::panic::resume_unwind(e);
385 }
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use serde_json::json;
393
394 fn with_temp_home<F: FnOnce()>(f: F) {
395 super::test_support::with_temp_home(f)
396 }
397
398 #[test]
399 fn config_dir_honors_wire_home() {
400 with_temp_home(|| {
401 let dir = config_dir().unwrap();
402 assert!(dir.ends_with("wire"), "got {dir:?}");
403 assert!(dir.to_string_lossy().contains("wire-test-"));
404 });
405 }
406
407 #[test]
408 fn ensure_dirs_creates_layout() {
409 with_temp_home(|| {
410 ensure_dirs().unwrap();
411 assert!(config_dir().unwrap().is_dir());
412 assert!(state_dir().unwrap().is_dir());
413 assert!(inbox_dir().unwrap().is_dir());
414 assert!(outbox_dir().unwrap().is_dir());
415 });
416 }
417
418 #[test]
419 fn private_key_roundtrip() {
420 with_temp_home(|| {
421 ensure_dirs().unwrap();
422 let seed = [42u8; 32];
423 write_private_key(&seed).unwrap();
424 let read_back = read_private_key().unwrap();
425 assert_eq!(seed, read_back);
426 });
427 }
428
429 #[test]
430 fn agent_card_roundtrip() {
431 with_temp_home(|| {
432 ensure_dirs().unwrap();
433 let card = json!({"did": "did:wire:paul", "name": "Paul"});
434 write_agent_card(&card).unwrap();
435 let read_back = read_agent_card().unwrap();
436 assert_eq!(card, read_back);
437 });
438 }
439
440 #[test]
441 fn trust_returns_empty_when_missing() {
442 with_temp_home(|| {
443 ensure_dirs().unwrap();
444 let t = read_trust().unwrap();
445 assert_eq!(t["version"], 1);
446 assert!(t["agents"].is_object());
447 });
448 }
449
450 #[test]
451 fn update_relay_state_writes_through_lock() {
452 with_temp_home(|| {
458 ensure_dirs().unwrap();
459 let initial = json!({"self": null, "peers": {}});
461 write_relay_state(&initial).unwrap();
462 super::update_relay_state(|state| {
464 state["self"] = json!({
465 "relay_url": "https://test",
466 "slot_id": "abc",
467 "slot_token": "tok",
468 });
469 Ok(())
470 })
471 .unwrap();
472 let after = read_relay_state().unwrap();
474 assert_eq!(after["self"]["relay_url"], "https://test");
475 assert_eq!(after["self"]["slot_id"], "abc");
476 });
477 }
478
479 #[test]
480 fn update_relay_state_modifier_error_does_not_clobber() {
481 with_temp_home(|| {
485 ensure_dirs().unwrap();
486 let initial = json!({"self": {"relay_url": "https://prior"}, "peers": {}});
487 write_relay_state(&initial).unwrap();
488 let result = super::update_relay_state(|state| {
489 state["self"] = json!({"relay_url": "https://NEVER_PERSIST"});
491 anyhow::bail!("simulated mid-RMW error")
493 });
494 assert!(result.is_err());
495 let after = read_relay_state().unwrap();
496 assert_eq!(
497 after["self"]["relay_url"], "https://prior",
498 "state on disk must not reflect aborted modifier"
499 );
500 });
501 }
502
503 #[test]
504 fn is_initialized_true_only_after_both_files_written() {
505 with_temp_home(|| {
506 ensure_dirs().unwrap();
507 assert!(!is_initialized().unwrap());
508 write_private_key(&[0u8; 32]).unwrap();
509 assert!(!is_initialized().unwrap()); write_agent_card(&json!({"did": "did:wire:paul"})).unwrap();
511 assert!(is_initialized().unwrap());
512 });
513 }
514
515 #[cfg(unix)]
516 #[test]
517 fn append_outbox_record_normalizes_fqdn_to_bare_handle() {
518 with_temp_home(|| {
522 let path_fqdn = append_outbox_record("bob@wireup.net", b"{\"kind\":1100}").unwrap();
523 let path_bare = append_outbox_record("bob", b"{\"kind\":1100}").unwrap();
524 assert_eq!(path_fqdn, path_bare, "FQDN form should normalize to bare");
526 assert!(
527 path_fqdn.file_name().unwrap().to_string_lossy() == "bob.jsonl",
528 "expected bob.jsonl, got {path_fqdn:?}"
529 );
530 let outbox = outbox_dir().unwrap();
532 assert!(
533 !outbox.join("bob@wireup.net.jsonl").exists(),
534 "FQDN-named file must not be created"
535 );
536 let body = std::fs::read_to_string(&path_bare).unwrap();
538 assert_eq!(body.matches("kind").count(), 2, "got: {body}");
539 });
540 }
541
542 #[test]
543 fn private_key_is_mode_0600() {
544 use std::os::unix::fs::PermissionsExt;
545 with_temp_home(|| {
546 ensure_dirs().unwrap();
547 write_private_key(&[1u8; 32]).unwrap();
548 let mode = fs::metadata(private_key_path().unwrap())
549 .unwrap()
550 .permissions()
551 .mode();
552 assert_eq!(mode & 0o777, 0o600, "got {:o}", mode & 0o777);
553 });
554 }
555}