File size: 7,029 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { writeFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";

function truncate(v, len = 40) {
  if (v == null) return "-";
  const s = String(v);
  return s.length > len ? s.slice(0, len - 1) + "…" : s;
}

function fmtTs(v) {
  if (!v) return "-";
  try {
    return new Date(v).toLocaleString();
  } catch {
    return String(v);
  }
}

function maskActor(v) {
  if (!v) return "-";
  const s = String(v);
  if (s.length <= 8) return s;
  return `${s.slice(0, 4)}****${s.slice(-4)}`;
}

const auditSchema = [
  { key: "timestamp", header: "Time", width: 22, formatter: fmtTs },
  { key: "source", header: "Source", width: 10 },
  { key: "actor", header: "Actor", width: 16, formatter: maskActor },
  { key: "action", header: "Action", width: 28 },
  { key: "resource", header: "Resource", width: 32, formatter: truncate },
  { key: "result", header: "Result", formatter: (v) => (v === "success" ? "✓" : "✗") },
  { key: "details", header: "Details", formatter: truncate },
];

function endpointFor(source) {
  return source === "mcp" ? "/api/mcp/audit" : "/api/compliance/audit-log";
}

async function fetchAuditEntries(sources, params) {
  const entries = [];
  for (const src of sources) {
    const endpoint = endpointFor(src);
    const res = await apiFetch(`${endpoint}?${params}`);
    if (!res.ok) continue;
    const data = await res.json();
    for (const e of data.items ?? data) {
      entries.push({ ...e, source: src });
    }
  }
  return entries;
}

function resolveSources(source) {
  if (source === "all") return ["compliance", "mcp"];
  return [source ?? "compliance"];
}

export async function runAuditTail(opts, cmd) {
  const globalOpts = cmd.optsWithGlobals();
  const sources = resolveSources(opts.source);
  const params = new URLSearchParams({ limit: String(opts.limit ?? 100) });
  const entries = await fetchAuditEntries(sources, params);
  entries.sort((a, b) => String(b.timestamp ?? "").localeCompare(String(a.timestamp ?? "")));
  emit(entries.slice(0, opts.limit ?? 100), globalOpts, auditSchema);

  if (opts.follow) {
    process.stderr.write("\n[following — Ctrl+C to exit]\n");
    let lastTs = entries[0]?.timestamp ?? new Date().toISOString();
    const loop = async () => {
      while (true) {
        await sleep(2000);
        for (const src of sources) {
          const endpoint = endpointFor(src);
          const res = await apiFetch(`${endpoint}?since=${encodeURIComponent(lastTs)}&limit=50`);
          if (!res.ok) continue;
          const data = await res.json();
          const newEntries = (data.items ?? data)
            .map((e) => ({ ...e, source: src }))
            .filter((e) => String(e.timestamp ?? "") > String(lastTs));
          for (const e of newEntries) {
            if (String(e.timestamp ?? "") > String(lastTs)) lastTs = e.timestamp;
            emit([e], globalOpts, auditSchema);
          }
        }
      }
    };
    process.on("SIGINT", () => process.exit(0));
    await loop();
  }
}

export async function runAuditSearch(query, opts, cmd) {
  const globalOpts = cmd.optsWithGlobals();
  const sources = resolveSources(opts.source);
  const params = new URLSearchParams({ q: query, limit: String(opts.limit ?? 200) });
  if (opts.since) params.set("since", opts.since);
  if (opts.until) params.set("until", opts.until);
  if (opts.actor) params.set("actor", opts.actor);
  if (opts.action) params.set("action", opts.action);
  const entries = await fetchAuditEntries(sources, params);
  entries.sort((a, b) => String(b.timestamp ?? "").localeCompare(String(a.timestamp ?? "")));
  emit(entries, globalOpts, auditSchema);
}

export async function runAuditExport(file, opts, cmd) {
  const sources = resolveSources(opts.source === "all" ? "compliance" : opts.source);
  const format = opts.format ?? "jsonl";
  const params = new URLSearchParams({ format });
  if (opts.since) params.set("since", opts.since);
  if (opts.until) params.set("until", opts.until);

  const allLines = [];
  for (const src of sources) {
    const endpoint = endpointFor(src);
    const res = await apiFetch(`${endpoint}?${params}`);
    if (!res.ok) {
      process.stderr.write(`Error fetching ${src}: ${res.status}\n`);
      continue;
    }
    const body = await res.text();
    allLines.push(body);
  }

  const combined = allLines.join("\n");
  writeFileSync(file, combined);
  process.stdout.write(`Exported to ${file} (${combined.length} bytes)\n`);
}

export async function runAuditStats(opts, cmd) {
  const globalOpts = cmd.optsWithGlobals();
  const source = opts.source ?? "mcp";
  const params = new URLSearchParams({ period: opts.period ?? "7d" });
  const endpoint = source === "mcp" ? "/api/mcp/audit/stats" : "/api/compliance/audit-log/stats";
  const res = await apiFetch(`${endpoint}?${params}`);
  if (!res.ok) {
    process.stderr.write(`Error: ${res.status}\n`);
    process.exit(1);
  }
  const data = await res.json();
  emit(data, globalOpts);
}

export async function runAuditGet(id, opts, cmd) {
  const globalOpts = cmd.optsWithGlobals();
  const source = opts.source ?? "compliance";
  const endpoint = endpointFor(source);
  const res = await apiFetch(`${endpoint}/${id}`);
  if (!res.ok) {
    process.stderr.write(`Not found: ${id}\n`);
    process.exit(1);
  }
  const data = await res.json();
  emit(data, globalOpts, auditSchema);
}

export function registerAudit(program) {
  const audit = program.command("audit").description(t("audit.description"));

  audit
    .command("tail")
    .description(t("audit.tail.description"))
    .option("--source <s>", t("audit.source"), "all")
    .option("--follow", t("audit.tail.follow"))
    .option("--limit <n>", t("audit.tail.limit"), parseInt, 100)
    .action(runAuditTail);

  audit
    .command("search <query>")
    .description(t("audit.search.description"))
    .option("--source <s>", t("audit.source"), "all")
    .option("--since <ts>", t("audit.since"))
    .option("--until <ts>", t("audit.until"))
    .option("--limit <n>", t("audit.search.limit"), parseInt, 200)
    .option("--actor <id>", t("audit.search.actor"))
    .option("--action <a>", t("audit.search.action"))
    .action(runAuditSearch);

  audit
    .command("export <file>")
    .description(t("audit.export.description"))
    .option("--source <s>", t("audit.source"), "all")
    .option("--format <f>", t("audit.export.format"), "jsonl")
    .option("--since <ts>", t("audit.since"))
    .option("--until <ts>", t("audit.until"))
    .action(runAuditExport);

  audit
    .command("stats")
    .description(t("audit.stats.description"))
    .option("--source <s>", t("audit.source"), "mcp")
    .option("--period <p>", t("audit.stats.period"), "7d")
    .action(runAuditStats);

  audit
    .command("get <id>")
    .description(t("audit.get.description"))
    .option("--source <s>", t("audit.source"), "compliance")
    .action(runAuditGet);
}