ek-api 0.1.0

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! 审计日志:写操作留痕(`%APPDATA%\ek\logs\audit-YYYYMMDD.log`)。
//!
//! 纪律:`detail` 只放键名/原因/计数,**绝不落值**(秘面值更不许)。

use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use crate::util;

/// 审计器(写操作前/后记一行 JSON)。
pub struct AuditLog {
    path: PathBuf,
    file: Mutex<Option<std::fs::File>>,
}

impl AuditLog {
    /// 建 `dir/audit-YYYYMMDD.log`(目录创建失败则退化为 stderr-only)。
    #[must_use]
    pub fn new(dir: &Path) -> Self {
        let (y, m, d) = util::today_utc();
        let path = dir.join(format!("audit-{y:04}{m:02}{d:02}.log"));
        let file = if fs::create_dir_all(dir).is_ok() {
            OpenOptions::new()
                .create(true)
                .append(true)
                .open(&path)
                .ok()
        } else {
            None
        };
        Self {
            path,
            file: Mutex::new(file),
        }
    }

    /// 审计文件路径。
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// 记一条。
    pub fn log(&self, user: &str, method: &str, target: &str, ok: bool, detail: &str) {
        let line = serde_json::json!({
            "at": crate::server::now_ms(),
            "user": user,
            "method": method,
            "target": target,
            "ok": ok,
            "detail": detail,
        })
        .to_string();
        eprintln!("[audit] {line}");
        if let Ok(mut g) = self.file.lock()
            && let Some(f) = g.as_mut()
        {
            let _ = writeln!(f, "{line}");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writes_json_line() {
        let dir = std::env::temp_dir().join(format!("ek-api-audit-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = AuditLog::new(&dir);
        a.log("alice", "cfg.save", "dm", true, "saved=true");
        let text = std::fs::read_to_string(a.path()).unwrap();
        let v: serde_json::Value = serde_json::from_str(text.trim()).unwrap();
        assert_eq!(v["user"], "alice");
        assert_eq!(v["method"], "cfg.save");
        assert_eq!(v["ok"], true);
        assert!(!text.contains("secret-value"));
        std::fs::remove_dir_all(&dir).ok();
    }
}