safesight-edge/agent/internal/audit/audit.go
2026-01-17 16:57:51 +08:00

57 lines
1.0 KiB
Go

package audit
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"rk3588sys/agent/internal/files"
)
type Entry struct {
TimeMS int64 `json:"time_ms"`
Action string `json:"action"`
Success bool `json:"success"`
RemoteIP string `json:"remote_ip,omitempty"`
TokenHash string `json:"token_hash,omitempty"`
Detail string `json:"detail,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
type Recorder struct {
mu sync.Mutex
path string
}
func NewRecorder(path string) *Recorder {
if path == "" {
return nil
}
return &Recorder{path: path}
}
func (r *Recorder) Record(entry Entry) error {
if r == nil {
return nil
}
b, err := json.Marshal(entry)
if err != nil {
return err
}
b = append(b, '\n')
r.mu.Lock()
defer r.mu.Unlock()
if err := files.EnsureDir(filepath.Dir(r.path), 0o755); err != nil {
return err
}
f, err := os.OpenFile(r.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(b)
return err
}