1use crate::input::HookInput;
2use crate::leaks;
3use crate::pii;
4use chrono::Utc;
5use serde::Serialize;
6use serde_json::Value;
7use std::fs;
8use std::io::Write;
9use std::path::PathBuf;
10
11#[derive(Serialize)]
12pub struct LogEntry {
13 pub timestamp: String,
14 pub session_id: Option<String>,
15 pub hook_event: String,
16 pub tool_name: Option<String>,
17 pub tool_input_summary: Option<String>,
18 pub cwd: Option<String>,
19 pub permission_mode: Option<String>,
20 pub duration_ms: Option<u64>,
21}
22
23impl LogEntry {
24 pub fn from_hook_input(input: &HookInput) -> Self {
25 let summary = extract_summary(input);
26 let redacted_summary = summary.map(|s| redact_sensitive(&truncate(&s, 200)));
27
28 LogEntry {
29 timestamp: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
30 session_id: input.session_id.clone(),
31 hook_event: input.hook_event_name.clone(),
32 tool_name: input.tool_name.clone(),
33 tool_input_summary: redacted_summary,
34 cwd: input.cwd.clone(),
35 permission_mode: input.permission_mode.clone(),
36 duration_ms: None,
37 }
38 }
39}
40
41fn extract_summary(input: &HookInput) -> Option<String> {
42 match input.hook_event_name.as_str() {
43 "PreToolUse" | "PostToolUse" => {
44 if let Some(tool_input) = &input.tool_input {
45 if let Some(cmd) = tool_input.get("command").and_then(Value::as_str) {
47 return Some(cmd.to_string());
48 }
49 if let Some(content) = tool_input.get("content").and_then(Value::as_str) {
50 return Some(content.to_string());
51 }
52 if let Some(new_str) = tool_input.get("new_string").and_then(Value::as_str) {
53 return Some(new_str.to_string());
54 }
55 return Some(tool_input.to_string());
57 }
58 None
59 }
60 "UserPromptSubmit" => input
61 .extra
62 .get("content")
63 .and_then(Value::as_str)
64 .map(String::from),
65 _ => None,
66 }
67}
68
69fn truncate(s: &str, max_len: usize) -> String {
70 if s.len() <= max_len {
71 s.to_string()
72 } else {
73 s[..max_len].to_string()
74 }
75}
76
77fn redact_sensitive(text: &str) -> String {
78 let mut result = pii::patterns::redact(text);
79 result = leaks::tier1::redact(&result);
80 result = leaks::tier2::redact(&result);
81 result = leaks::tier3::redact(&result);
82 result
83}
84
85fn get_log_path() -> PathBuf {
86 if let Ok(custom) = std::env::var("WARD_LOG_PATH") {
87 PathBuf::from(custom)
88 } else {
89 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
90 PathBuf::from(home).join(".ward").join("events.jsonl")
91 }
92}
93
94pub fn append_to_log(entry: &LogEntry) -> std::io::Result<()> {
95 append_to_log_at(&get_log_path(), entry)
96}
97
98pub fn append_to_log_at(path: &std::path::Path, entry: &LogEntry) -> std::io::Result<()> {
99
100 if let Some(parent) = path.parent() {
102 fs::create_dir_all(parent)?;
103 }
104
105 let json = serde_json::to_string(entry)?;
106
107 let mut file = fs::OpenOptions::new()
108 .create(true)
109 .append(true)
110 .open(&path)?;
111
112 writeln!(file, "{}", json)?;
113
114 Ok(())
115}