feat: 审计 CSV 导出 — 用户/API Key/集群操作日志一键下载

新增端点 (read 级, 审计 viewer 角色即可导出):
- GET /audit/users.csv: 账号清单 + 最后登录时间
- GET /audit/apikeys.csv: 密钥清单 (前缀+scope+最后使用+过期)
- GET /audit/cluster-log.csv: 令牌环操作日志时间线
  (seq/time_utc/node/kind/detail/data_json 六列, detail 为人读摘要,
   data_json 保留无损原始载荷)

安全设计:
- RFC4180 转义 (引号/逗号/换行)
- 公式注入防御: =/+/@/tab/- 开头单元格加 ' 前缀
- ISO8601 UTC 时间戳, Excel 直接排序
- 明文密钥不可逆, 仅导出展示前缀

前端:
- UsersView: 账号表/API 密钥表各加「⤓ 导出 CSV」按钮
- ClusterView: 日志导出下拉新增 CSV 选项 (走服务端生成)
- api.ts: downloadAuditCsv() 统一下载管道

测试: csvEscape 全用例 / users+apikeys CSV 内容断言 / 未认证 401
This commit is contained in:
JianFeeeee
2026-08-24 22:52:32 +08:00
parent 4a41608d94
commit ef98d9dca1
10 changed files with 645 additions and 231 deletions

View File

@ -1,232 +1,274 @@
// HTTP client and API functions for webui4frpc.
import type {
ApiKey,
ApiKeyCreated,
BinaryStatus,
CacheResp,
CanvasData,
CanvasExportEnvelope,
ClusterNodesResp,
InstallResult,
MeResp,
Remote,
RingSnapshot,
Settings,
StatusResp,
User,
WorkerLogBundle,
ApiKey,
ApiKeyCreated,
BinaryStatus,
CacheResp,
CanvasData,
CanvasExportEnvelope,
ClusterNodesResp,
InstallResult,
MeResp,
Remote,
RingSnapshot,
Settings,
StatusResp,
User,
WorkerLogBundle,
} from "./types";
class HTTPError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const response = await fetch(url, {
credentials: "same-origin",
...options,
});
if (!response.ok) {
throw new HTTPError(response.status, `HTTP ${response.status}`);
}
const ct = response.headers.get("content-type") || "";
if (ct.includes("application/json")) {
return response.json() as Promise<T>;
}
return response.text() as unknown as Promise<T>;
const response = await fetch(url, {
credentials: "same-origin",
...options,
});
if (!response.ok) {
throw new HTTPError(response.status, `HTTP ${response.status}`);
}
const ct = response.headers.get("content-type") || "";
if (ct.includes("application/json")) {
return response.json() as Promise<T>;
}
return response.text() as unknown as Promise<T>;
}
const json = (body: unknown): RequestInit => ({
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
export const api = {
status: () => request<StatusResp>("/api/manager/status"),
status: () => request<StatusResp>("/api/manager/status"),
canvas: () => request<CanvasData>("/api/manager/canvas"),
saveCanvas: (data: CanvasData) =>
request<CanvasData>("/api/manager/canvas", json(data)),
canvas: () => request<CanvasData>("/api/manager/canvas"),
saveCanvas: (data: CanvasData) =>
request<CanvasData>("/api/manager/canvas", json(data)),
settings: () => request<Settings>("/api/manager/settings"),
saveSettings: (s: Settings) =>
request<Settings>("/api/manager/settings", json(s)),
settings: () => request<Settings>("/api/manager/settings"),
saveSettings: (s: Settings) =>
request<Settings>("/api/manager/settings", json(s)),
binaryStatus: () => request<BinaryStatus>("/api/manager/binary/status"),
installBinary: (version?: string) =>
request<InstallResult>("/api/manager/binary/install", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: version ? JSON.stringify({ version }) : undefined,
}),
binaryStatus: () => request<BinaryStatus>("/api/manager/binary/status"),
installBinary: (version?: string) =>
request<InstallResult>("/api/manager/binary/install", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: version ? JSON.stringify({ version }) : undefined,
}),
saveRemote: (remote: Remote) =>
request<Remote>("/api/manager/remotes", json(remote)),
deleteRemote: (name: string) =>
request<void>(`/api/manager/remotes/${encodeURIComponent(name)}`, {
method: "DELETE",
}),
saveRemote: (remote: Remote) =>
request<Remote>("/api/manager/remotes", json(remote)),
deleteRemote: (name: string) =>
request<void>(`/api/manager/remotes/${encodeURIComponent(name)}`, {
method: "DELETE",
}),
// Add a single link (POST /links). The canvas save path (saveCanvas) does a
// wholesale link replace, so this is for incremental single-link adds from
// other surfaces (e.g. a forwards list). For a cluster (non-localOnly)
// forward the backend also submits a ring task so the owning node claims it.
addLink: (link: {
local: string;
remote: string;
remotePort: number;
group?: string;
}) =>
request<import("./types").Link>(`/api/manager/links`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(link),
}),
// Add a single link (POST /links). The canvas save path (saveCanvas) does a
// wholesale link replace, so this is for incremental single-link adds from
// other surfaces (e.g. a forwards list). For a cluster (non-localOnly)
// forward the backend also submits a ring task so the owning node claims it.
addLink: (link: {
local: string;
remote: string;
remotePort: number;
group?: string;
}) =>
request<import("./types").Link>(`/api/manager/links`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(link),
}),
// Delete a single link by id. When present in the canvas save payload,
// links are replaced wholesale, so the typical path is "remove from
// canvas edges + save". This endpoint is kept for explicit removal
// (e.g. delete from a forwards list) — it also revokes cluster tasks
// for the removed forward.
deleteLink: (id: number) =>
request<void>(`/api/manager/links/${id}`, { method: "DELETE" }),
// Delete a single link by id. When present in the canvas save payload,
// links are replaced wholesale, so the typical path is "remove from
// canvas edges + save". This endpoint is kept for explicit removal
// (e.g. delete from a forwards list) — it also revokes cluster tasks
// for the removed forward.
deleteLink: (id: number) =>
request<void>(`/api/manager/links/${id}`, { method: "DELETE" }),
// Per-forward start/stop (forwards page). local-only forwards toggle the
// local frpc worker; cluster forwards submit/revoke via the ring.
forwardStart: (local: string, remote: string, remotePort: number) =>
request<{ ok: boolean }>("/api/manager/forwards/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort }),
}),
forwardStop: (local: string, remote: string, remotePort: number) =>
request<{ ok: boolean }>("/api/manager/forwards/stop", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort }),
}),
groupStart: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
groupStop: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/stop", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
// assignGroup changes a single forward's group label (status page chip).
// Empty group clears the assignment (移出分组). Pure DB update, no worker.
assignGroup: (local: string, remote: string, remotePort: number, group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/assign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort, group }),
}),
// deleteGroup dissolves a group: all members moved to 未分组. The group is
// just a label on links, so clearing all members is the complete delete.
deleteGroup: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
// Per-forward start/stop (forwards page). local-only forwards toggle the
// local frpc worker; cluster forwards submit/revoke via the ring.
forwardStart: (local: string, remote: string, remotePort: number) =>
request<{ ok: boolean }>("/api/manager/forwards/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort }),
}),
forwardStop: (local: string, remote: string, remotePort: number) =>
request<{ ok: boolean }>("/api/manager/forwards/stop", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort }),
}),
groupStart: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
groupStop: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/stop", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
// assignGroup changes a single forward's group label (status page chip).
// Empty group clears the assignment (移出分组). Pure DB update, no worker.
assignGroup: (
local: string,
remote: string,
remotePort: number,
group: string,
) =>
request<{ ok: boolean }>("/api/manager/forwards/assign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ local, remote, remotePort, group }),
}),
// deleteGroup dissolves a group: all members moved to 未分组. The group is
// just a label on links, so clearing all members is the complete delete.
deleteGroup: (group: string) =>
request<{ ok: boolean }>("/api/manager/forwards/group/delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ group }),
}),
profileStart: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/start`, {
method: "POST",
}),
profileStop: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/stop`, {
method: "POST",
}),
profileRestart: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/restart`, {
method: "POST",
}),
profileConfig: (name: string) =>
request<string>(`/api/manager/profiles/${encodeURIComponent(name)}/config`),
profileLogs: (name: string) =>
request<string>(`/api/manager/profiles/${encodeURIComponent(name)}/logs`),
profileStart: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/start`, {
method: "POST",
}),
profileStop: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/stop`, {
method: "POST",
}),
profileRestart: (name: string) =>
request<void>(`/api/manager/profiles/${encodeURIComponent(name)}/restart`, {
method: "POST",
}),
profileConfig: (name: string) =>
request<string>(`/api/manager/profiles/${encodeURIComponent(name)}/config`),
profileLogs: (name: string) =>
request<string>(`/api/manager/profiles/${encodeURIComponent(name)}/logs`),
// M6: cluster nodes + binary cache management.
clusterNodes: () => request<ClusterNodesResp>("/api/manager/cluster/nodes"),
clusterCache: () => request<CacheResp>("/api/manager/cluster/cache"),
pruneCache: (keep: number) =>
request<CacheResp>("/api/manager/cluster/cache", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ keep }),
}),
// M6: cluster nodes + binary cache management.
clusterNodes: () => request<ClusterNodesResp>("/api/manager/cluster/nodes"),
clusterCache: () => request<CacheResp>("/api/manager/cluster/cache"),
pruneCache: (keep: number) =>
request<CacheResp>("/api/manager/cluster/cache", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ keep }),
}),
// M6 token ring snapshot.
ring: () => request<RingSnapshot>("/api/manager/cluster/ring"),
// M6 token ring snapshot.
ring: () => request<RingSnapshot>("/api/manager/cluster/ring"),
// M6 cluster lifecycle (创建/加入/退出/移除).
// clusterCreate: reseed THIS node as a fresh standalone leader (创建集群).
clusterCreate: () =>
request<RingSnapshot>("/api/manager/cluster/create", { method: "POST" }),
// clusterJoinRing: THIS node joins the cluster at peer addr (加入集群).
// joinKey is the sponsor node's nodeKey — required for admission security.
clusterJoinRing: (addr: string, joinKey: string) =>
request<RingSnapshot>("/api/manager/cluster/join-ring", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ addr, joinKey }),
}),
// clusterRemoveNode: publish a node-removal command (移除节点 / 退出集群[self]).
clusterRemoveNode: (id: string) =>
request<{ task: unknown }>("/api/manager/cluster/node-remove", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id }),
}),
// M6 cluster lifecycle (创建/加入/退出/移除).
// clusterCreate: reseed THIS node as a fresh standalone leader (创建集群).
clusterCreate: () =>
request<RingSnapshot>("/api/manager/cluster/create", { method: "POST" }),
// clusterJoinRing: THIS node joins the cluster at peer addr (加入集群).
// joinKey is the sponsor node's nodeKey — required for admission security.
clusterJoinRing: (addr: string, joinKey: string) =>
request<RingSnapshot>("/api/manager/cluster/join-ring", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ addr, joinKey }),
}),
// clusterRemoveNode: publish a node-removal command (移除节点 / 退出集群[self]).
clusterRemoveNode: (id: string) =>
request<{ task: unknown }>("/api/manager/cluster/node-remove", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id }),
}),
// M7 auth/accounts/API keys/canvas export-import/worker logs.
me: () => request<MeResp>("/api/manager/me"),
listUsers: () => request<{ users: User[] }>("/api/manager/users"),
createUser: (username: string, password: string, role: 'admin' | 'viewer') =>
request<User>("/api/manager/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, role }),
}),
updateUser: (name: string, patch: { password?: string; role?: 'admin' | 'viewer'; enabled?: boolean }) =>
request<User>(`/api/manager/users/${encodeURIComponent(name)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
}),
deleteUser: (name: string) =>
request<void>(`/api/manager/users/${encodeURIComponent(name)}`, {
method: "DELETE",
}),
listApiKeys: () => request<{ apiKeys: ApiKey[] }>("/api/manager/apikeys"),
createApiKey: (userId: number, label: string, scope: 'read' | 'write' | 'admin') =>
request<ApiKeyCreated>("/api/manager/apikeys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, label, scope }),
}),
deleteApiKey: (id: number) =>
request<void>(`/api/manager/apikeys/${id}`, { method: "DELETE" }),
// M7 auth/accounts/API keys/canvas export-import/worker logs.
me: () => request<MeResp>("/api/manager/me"),
listUsers: () => request<{ users: User[] }>("/api/manager/users"),
createUser: (username: string, password: string, role: "admin" | "viewer") =>
request<User>("/api/manager/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, role }),
}),
updateUser: (
name: string,
patch: { password?: string; role?: "admin" | "viewer"; enabled?: boolean },
) =>
request<User>(`/api/manager/users/${encodeURIComponent(name)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
}),
deleteUser: (name: string) =>
request<void>(`/api/manager/users/${encodeURIComponent(name)}`, {
method: "DELETE",
}),
listApiKeys: () => request<{ apiKeys: ApiKey[] }>("/api/manager/apikeys"),
createApiKey: (
userId: number,
label: string,
scope: "read" | "write" | "admin",
) =>
request<ApiKeyCreated>("/api/manager/apikeys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, label, scope }),
}),
deleteApiKey: (id: number) =>
request<void>(`/api/manager/apikeys/${id}`, { method: "DELETE" }),
// Canvas export/import (转发表 备份/还原).
exportCanvas: () => request<CanvasExportEnvelope>("/api/manager/canvas/export"),
importCanvas: (data: CanvasData | CanvasExportEnvelope) =>
request<CanvasData>("/api/manager/canvas/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}),
// Canvas export/import (转发表 备份/还原).
exportCanvas: () =>
request<CanvasExportEnvelope>("/api/manager/canvas/export"),
importCanvas: (data: CanvasData | CanvasExportEnvelope) =>
request<CanvasData>("/api/manager/canvas/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}),
// Worker-log bundle (HTTP fan-out across ring nodes; read-level/auditor).
exportWorkerLogs: () => request<WorkerLogBundle>("/api/manager/cluster/logs/export"),
// Worker-log bundle (HTTP fan-out across ring nodes; read-level/auditor).
exportWorkerLogs: () =>
request<WorkerLogBundle>("/api/manager/cluster/logs/export"),
// ---- Audit CSV exports (read-level) ----
// downloadCsv fetches a CSV endpoint with credentials and triggers a file
// download. Kept here so views don't repeat the blob plumbing.
};
// downloadAuditCsv streams one of the /audit/*.csv endpoints to a file.
export async function downloadAuditCsv(
kind: "users" | "apikeys" | "cluster-log",
): Promise<void> {
const resp = await fetch(`/api/manager/audit/${kind}.csv`, {
credentials: "same-origin",
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const disposition = resp.headers.get("content-disposition") || "";
const m = disposition.match(/filename="?([^";]+)"?/);
const filename = m?.[1] ?? `audit-${kind}.csv`;
const blob = new Blob([await resp.text()], {
type: "text/csv;charset=utf-8",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}

View File

@ -150,6 +150,7 @@
<el-dropdown-menu>
<el-dropdown-item command="json">JSON完整结构</el-dropdown-item>
<el-dropdown-item command="txt">文本可读 TSV</el-dropdown-item>
<el-dropdown-item command="csv">CSV审计用Excel 可开</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
@ -194,7 +195,7 @@
<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '../api'
import { api, downloadAuditCsv } from '../api'
import type { RingSnapshot, RingTaskInfo, RingLogEntry } from '../types'
const ring = ref<RingSnapshot | null>(null)
@ -321,8 +322,18 @@ const detailOf = (e: RingLogEntry): string => {
}
}
// exportLog downloads the FULL cluster log (snapshot carries every entry) as
// either pretty JSON (lossless) or a readable TSV text file, sorted by seq.
const exportLog = (fmt: string) => {
// pretty JSON (lossless), a readable TSV text file, or server-generated RFC4180
// CSV (audit deliverable, Excel-friendly) — sorted by seq.
const exportLog = async (fmt: string) => {
if (fmt === 'csv') {
// Server-side CSV: RFC4180 escaping + formula-injection defence + ISO8601 UTC.
try {
await downloadAuditCsv('cluster-log')
} catch (e: any) {
ElMessage.error('导出失败: ' + (e?.message || e))
}
return
}
const entries = [...(ring.value?.log ?? [])].sort((a, b) => a.seq - b.seq)
if (!entries.length) return
let content = ''

View File

@ -10,7 +10,10 @@
<section class="card">
<header class="card-h">
<h3>账号</h3>
<el-button type="primary" size="small" @click="openUserCreate"> 新建账号</el-button>
<div class="h-actions">
<el-button size="small" @click="exportCsv('users')"> 导出 CSV</el-button>
<el-button type="primary" size="small" @click="openUserCreate"> 新建账号</el-button>
</div>
</header>
<el-table :data="users" size="small" stripe empty-text="暂无账号">
<el-table-column prop="username" label="用户名" min-width="140" />
@ -55,7 +58,10 @@
<section class="card">
<header class="card-h">
<h3>API 密钥</h3>
<el-button type="primary" size="small" @click="openKeyCreate"> 新建密钥</el-button>
<div class="h-actions">
<el-button size="small" @click="exportCsv('apikeys')"> 导出 CSV</el-button>
<el-button type="primary" size="small" @click="openKeyCreate"> 新建密钥</el-button>
</div>
</header>
<el-table :data="apiKeys" size="small" stripe empty-text="暂无密钥">
<el-table-column prop="label" label="标签" min-width="140" />
@ -150,12 +156,23 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { api } from '../api'
import { api, downloadAuditCsv } from '../api'
import type { ApiKey, ApiKeyCreated, User } from '../types'
const users = ref<User[]>([])
const apiKeys = ref<ApiKey[]>([])
// exportCsv streams one of the audit CSV endpoints to a file. Read-level:
// auditors pull these without any write permission.
const exportCsv = async (kind: 'users' | 'apikeys') => {
try {
await downloadAuditCsv(kind)
ElMessage.success('已导出 CSV')
} catch (e: any) {
ElMessage.error('导出失败: ' + (e?.message || e))
}
}
const loadUsers = async () => {
const r = await api.listUsers()
users.value = r.users