feat(app): M5 step 1, the admin backend under the management app

- datadir: the data folder layout, the location file (JARVIS_DATA_DIR wins),
  free space for the wizard.
- settings_edit: the fields the five settings screens edit; apply writes only
  non-defaults, keeps unknown keys and writes nothing unless the app's own
  check passes. A memory section reaches the worker's hello.
- secrets: config/secrets.dat, DPAPI for the Windows user; the services take
  the bot token from it before JARVIS_DISCORD_TOKEN.
- logs: the log hub behind the log screen (tabs, daily files kept 14 days,
  the recent error report, a zip under 10 MB, secrets and token-shaped text
  masked); the log macros and the worker's output feed it.

Spec: app/src/admin.spec.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 13:35:59 +09:00
parent 07c701be54
commit 390f6f0b86
18 changed files with 1457 additions and 19 deletions

181
app/src/secrets.rs Normal file
View File

@@ -0,0 +1,181 @@
//! Stored secrets, `config/secrets.dat` (`app/src/admin.spec.md`): DPAPI-encrypted for the Windows
//! user; plain JSON with owner-only permissions elsewhere (development only).
use std::path::{Path, PathBuf};
use serde_json::{Map, Value};
use crate::datadir::write_atomic;
/// The Discord bot token's name in the store.
pub const DISCORD_TOKEN: &str = "discordToken";
#[derive(Debug)]
pub struct SecretsError(pub String);
impl std::fmt::Display for SecretsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for SecretsError {}
pub struct Secrets {
file: PathBuf,
}
impl Secrets {
pub fn new(file: &Path) -> Self {
Self { file: file.to_path_buf() }
}
fn load(&self) -> Result<Map<String, Value>, SecretsError> {
let bytes = match std::fs::read(&self.file) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Map::new()),
Err(e) => return Err(SecretsError(format!("could not read the secrets: {e}"))),
};
let plain = unprotect(&bytes)?;
match serde_json::from_slice(&plain) {
Ok(Value::Object(m)) => Ok(m),
_ => Err(SecretsError("the secrets file is damaged".into())),
}
}
fn save(&self, m: &Map<String, Value>) -> Result<(), SecretsError> {
let plain = serde_json::to_vec(m).expect("a map serialises");
let bytes = protect(&plain)?;
write_atomic(&self.file, &bytes).map_err(|e| SecretsError(format!("could not write the secrets: {e}")))?;
restrict(&self.file);
Ok(())
}
pub fn get(&self, name: &str) -> Result<Option<String>, SecretsError> {
Ok(self.load()?.get(name).and_then(Value::as_str).map(str::to_owned))
}
pub fn set(&self, name: &str, value: &str) -> Result<(), SecretsError> {
let mut m = self.load()?;
m.insert(name.into(), Value::String(value.into()));
self.save(&m)
}
pub fn remove(&self, name: &str) -> Result<(), SecretsError> {
let mut m = self.load()?;
if m.remove(name).is_some() {
self.save(&m)?;
}
Ok(())
}
/// Every stored value, for log redaction.
pub fn values(&self) -> Vec<String> {
self.load().map(|m| m.values().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default()
}
}
/// Only the last 4 characters, for the screens: `••••abcd`.
pub fn masked(value: &str) -> String {
let chars: Vec<char> = value.chars().collect();
let tail: String = chars[chars.len().saturating_sub(4)..].iter().collect();
format!("••••{tail}")
}
#[cfg(unix)]
fn restrict(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(not(unix))]
fn restrict(_: &Path) {}
#[cfg(not(windows))]
fn protect(plain: &[u8]) -> Result<Vec<u8>, SecretsError> {
Ok(plain.to_vec())
}
#[cfg(not(windows))]
fn unprotect(bytes: &[u8]) -> Result<Vec<u8>, SecretsError> {
Ok(bytes.to_vec())
}
#[cfg(windows)]
fn dpapi(input: &[u8], encrypt: bool) -> Result<Vec<u8>, SecretsError> {
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Cryptography::{
CryptProtectData, CryptUnprotectData, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB,
};
let data_in = CRYPT_INTEGER_BLOB { cbData: input.len() as u32, pbData: input.as_ptr() as *mut u8 };
let mut out = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() };
// SAFETY: the input blob points at `input` for the call; the output is freed with LocalFree.
let ok = unsafe {
if encrypt {
CryptProtectData(&data_in, std::ptr::null(), std::ptr::null(), std::ptr::null(), std::ptr::null(),
CRYPTPROTECT_UI_FORBIDDEN, &mut out)
} else {
CryptUnprotectData(&data_in, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null(),
CRYPTPROTECT_UI_FORBIDDEN, &mut out)
}
};
if ok == 0 {
return Err(SecretsError(if encrypt { "could not encrypt the secrets".into() } else {
"could not decrypt the secrets (another Windows user or PC?)".into() }));
}
// SAFETY: DPAPI returned `cbData` bytes at `pbData`.
let v = unsafe { std::slice::from_raw_parts(out.pbData, out.cbData as usize).to_vec() };
unsafe { LocalFree(out.pbData as _) };
Ok(v)
}
#[cfg(windows)]
fn protect(plain: &[u8]) -> Result<Vec<u8>, SecretsError> {
dpapi(plain, true)
}
#[cfg(windows)]
fn unprotect(bytes: &[u8]) -> Result<Vec<u8>, SecretsError> {
dpapi(bytes, false)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::datadir::temp_dir;
#[test]
fn secrets_round_trip_and_are_removed() {
let s = Secrets::new(&temp_dir("sec").join("config").join("secrets.dat"));
assert_eq!(s.get(DISCORD_TOKEN).unwrap(), None);
s.set(DISCORD_TOKEN, "abc.def.ghij").unwrap();
s.set("other", "x").unwrap();
assert_eq!(s.get(DISCORD_TOKEN).unwrap().as_deref(), Some("abc.def.ghij"));
let mut v = s.values();
v.sort();
assert_eq!(v, vec!["abc.def.ghij", "x"]);
s.remove(DISCORD_TOKEN).unwrap();
assert_eq!(s.get(DISCORD_TOKEN).unwrap(), None);
assert_eq!(s.get("other").unwrap().as_deref(), Some("x"));
}
#[cfg(unix)]
#[test]
fn the_file_is_readable_by_its_owner_only() {
use std::os::unix::fs::PermissionsExt;
let f = temp_dir("secp").join("secrets.dat");
Secrets::new(&f).set(DISCORD_TOKEN, "t").unwrap();
assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600);
}
#[test]
fn a_damaged_file_is_reported_not_overwritten() {
let f = temp_dir("secd").join("secrets.dat");
std::fs::write(&f, b"not json").unwrap();
let s = Secrets::new(&f);
assert!(s.get(DISCORD_TOKEN).is_err());
assert!(s.set(DISCORD_TOKEN, "t").is_err());
assert_eq!(std::fs::read(&f).unwrap(), b"not json");
}
#[test]
fn masking_shows_only_the_last_four() {
assert_eq!(masked("MTIz.abcd.wxyz"), "••••wxyz");
assert_eq!(masked("ab"), "••••ab");
}
}