mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-11-19 15:03:21 +00:00
feat(security): 操作审计日志 + 会话IP/UA绑定 + 敏感操作 step-up 2FA
应对管理员访问凭证失守导致的数据外泄风险,新增三层防护: 审计日志(admin-only 可见,用户不可见) - 新增 append-only audit_logs 表(migration 180)+ 异步批量写入 + 保留期清理 - 审计中间件挂在 admin/user/auth/admin-payment 组认证之后:记录所有变更类 请求 + 白名单敏感读取(账号/代理导出、备份下载、admin/user API key 读取) - 请求头凭证首尾掩码;请求体 JSON 递归脱敏(api_key/password 等擦除,base_url 保留以便追责);非 JSON body 不入库 - 无单条删除;全量清空需现场 TOTP 校验、拒绝 admin API key、未启用 2FA 不允许, 清空后同步写入留痕记录 会话 IP/UA 绑定(默认开启,可在系统设置关闭) - JWT 携带 session id + IP/UA 指纹哈希;IP 或 UA 任一变化即撤销会话家族并要求 重新登录;旧 token 无指纹时放行以平滑升级 敏感操作 step-up 2FA(sudo 窗口 15 分钟) - 账号/代理导出、DB 备份创建/下载、S3 目标修改要求近期 TOTP 二次验证;admin API key 一律拒绝;前端 useStepUp 组合式 + TotpStepUpDialog 弹码后自动重试 - API key 查看按需求暂不加强管控 前端:新增 /admin/audit-logs 操作日志页面(筛选/详情/2FA 清空)、侧边栏入口、 step-up 弹窗接入导出与备份流程、安全设置项(绑定开关 + 日志保留天数)、zh/en i18n
This commit is contained in:
1 parent
09c6c6d740
commit
0ddd58aaf9
69 files changed
+3124
-75
No files matched your search
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Admin operation audit log API.
|
||||
*
|
||||
* The audit log is admin-only (not exposed to end users). It records
|
||||
* management-plane operations with masked header credentials and redacted
|
||||
* request bodies. Entries cannot be deleted individually; the whole log can
|
||||
* only be cleared with a fresh TOTP verification.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../client'
|
||||
import type { PaginatedResponse } from '@/types'
|
||||
|
||||
export interface AuditLog {
|
||||
id: number
|
||||
created_at: string
|
||||
actor_user_id?: number
|
||||
actor_email: string
|
||||
actor_role: string
|
||||
auth_method: string
|
||||
credential_masked: string
|
||||
action: string
|
||||
method: string
|
||||
path: string
|
||||
request_id: string
|
||||
client_ip: string
|
||||
user_agent: string
|
||||
request_body?: string
|
||||
status_code: number
|
||||
latency_ms: number
|
||||
extra?: Record<string, any>
|
||||
}
|
||||
|
||||
export interface AuditLogQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
start_time?: string
|
||||
end_time?: string
|
||||
actor_user_id?: number
|
||||
actor_email?: string
|
||||
auth_method?: string
|
||||
action?: string
|
||||
method?: string
|
||||
client_ip?: string
|
||||
success?: string
|
||||
q?: string
|
||||
}
|
||||
|
||||
export type AuditLogListResponse = PaginatedResponse<AuditLog>
|
||||
|
||||
/**
|
||||
* List audit logs (paginated, filterable).
|
||||
*/
|
||||
export async function list(params: AuditLogQuery): Promise<AuditLogListResponse> {
|
||||
const { data } = await apiClient.get('/admin/audit-logs', { params })
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single audit log entry (includes the redacted request body).
|
||||
*/
|
||||
export async function get(id: number): Promise<AuditLog> {
|
||||
const { data } = await apiClient.get(`/admin/audit-logs/${id}`)
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all audit logs. Requires a fresh TOTP code (verified server-side);
|
||||
* unavailable when 2FA is not enabled for the operator.
|
||||
* @param totpCode - current 6-digit TOTP code
|
||||
*/
|
||||
export async function clear(totpCode: string): Promise<{ deleted: number }> {
|
||||
const { data } = await apiClient.post('/admin/audit-logs/clear', { totp_code: totpCode })
|
||||
return data
|
||||
}
|
||||
|
||||
export const auditAPI = {
|
||||
list,
|
||||
get,
|
||||
clear
|
||||
}
|
||||
|
||||
export default auditAPI
|
||||
@@ -33,6 +33,7 @@ import adminPaymentAPI from './payment'
|
||||
import affiliatesAPI from './affiliates'
|
||||
import riskControlAPI from './riskControl'
|
||||
import adminComplianceAPI from './compliance'
|
||||
import auditAPI from './audit'
|
||||
|
||||
/**
|
||||
* Unified admin API object for convenient access
|
||||
@@ -67,7 +68,8 @@ export const adminAPI = {
|
||||
payment: adminPaymentAPI,
|
||||
affiliates: affiliatesAPI,
|
||||
riskControl: riskControlAPI,
|
||||
compliance: adminComplianceAPI
|
||||
compliance: adminComplianceAPI,
|
||||
audit: auditAPI
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -100,12 +102,14 @@ export {
|
||||
adminPaymentAPI,
|
||||
affiliatesAPI,
|
||||
riskControlAPI,
|
||||
adminComplianceAPI
|
||||
adminComplianceAPI,
|
||||
auditAPI
|
||||
}
|
||||
|
||||
export default adminAPI
|
||||
|
||||
// Re-export types used by components
|
||||
export type { AuditLog, AuditLogQuery, AuditLogListResponse } from './audit'
|
||||
export type { BalanceHistoryItem } from './users'
|
||||
export type { ErrorPassthroughRule, CreateRuleRequest, UpdateRuleRequest } from './errorPassthrough'
|
||||
export type { BackupAgentHealth, DataManagementConfig } from './dataManagement'
|
||||
|
||||
@@ -366,6 +366,8 @@ export interface SystemSettings {
|
||||
invitation_code_enabled: boolean;
|
||||
totp_enabled: boolean; // TOTP 双因素认证
|
||||
totp_encryption_key_configured: boolean; // TOTP 加密密钥是否已配置
|
||||
session_binding_enabled: boolean; // 会话 IP/UA 绑定
|
||||
audit_log_retention_days: number; // 审计日志保留天数
|
||||
login_agreement_enabled: boolean;
|
||||
login_agreement_mode: "modal" | "checkbox" | string;
|
||||
login_agreement_updated_at: string;
|
||||
@@ -669,6 +671,8 @@ export interface UpdateSettingsRequest {
|
||||
frontend_url?: string;
|
||||
invitation_code_enabled?: boolean;
|
||||
totp_enabled?: boolean; // TOTP 双因素认证
|
||||
session_binding_enabled?: boolean; // 会话 IP/UA 绑定
|
||||
audit_log_retention_days?: number; // 审计日志保留天数
|
||||
login_agreement_enabled?: boolean;
|
||||
login_agreement_mode?: "modal" | "checkbox" | string;
|
||||
login_agreement_updated_at?: string;
|
||||
|
||||
@@ -71,13 +71,32 @@ export async function disable(request: TotpDisableRequest): Promise<{ success: b
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Step-up verification response
|
||||
*/
|
||||
export interface TotpStepUpResponse {
|
||||
verified: boolean
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a TOTP code to grant the current session a short-lived step-up
|
||||
* (sudo) window for sensitive operations (account export, DB backup download...).
|
||||
* @param code - 6-digit TOTP code
|
||||
*/
|
||||
export async function stepUp(code: string): Promise<TotpStepUpResponse> {
|
||||
const { data } = await apiClient.post<TotpStepUpResponse>('/user/totp/step-up', { code })
|
||||
return data
|
||||
}
|
||||
|
||||
export const totpAPI = {
|
||||
getStatus,
|
||||
getVerificationMethod,
|
||||
sendVerifyCode,
|
||||
initiateSetup,
|
||||
enable,
|
||||
disable
|
||||
disable,
|
||||
stepUp
|
||||
}
|
||||
|
||||
export default totpAPI
|
||||
@@ -0,0 +1,179 @@
|
||||
<template>
|
||||
<div v-if="controller.visible.value" class="fixed inset-0 z-[60] overflow-y-auto">
|
||||
<div class="flex min-h-full items-center justify-center p-4">
|
||||
<div class="fixed inset-0 bg-black/50 transition-opacity" @click="handleCancel"></div>
|
||||
|
||||
<div class="relative w-full max-w-md transform rounded-xl bg-white p-6 shadow-xl transition-all dark:bg-dark-800">
|
||||
<div class="mb-6 text-center">
|
||||
<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-primary-100 dark:bg-primary-900/30">
|
||||
<svg class="h-6 w-6 text-primary-600 dark:text-primary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 class="mt-4 text-xl font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('stepUp.title') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ t('stepUp.hint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<input
|
||||
ref="hiddenOtpInputRef"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
autocomplete="one-time-code"
|
||||
maxlength="6"
|
||||
class="pointer-events-none absolute left-0 top-0 h-px w-px opacity-0"
|
||||
aria-hidden="true"
|
||||
tabindex="-1"
|
||||
@input="handleHiddenOtpInput"
|
||||
/>
|
||||
<div class="flex justify-center gap-2">
|
||||
<input
|
||||
v-for="(_, index) in 6"
|
||||
:key="index"
|
||||
:ref="(el) => setInputRef(el, index)"
|
||||
type="text"
|
||||
maxlength="1"
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]"
|
||||
autocomplete="off"
|
||||
class="h-12 w-10 rounded-lg border border-gray-300 text-center text-lg font-semibold focus:border-primary-500 focus:ring-primary-500 dark:border-dark-600 dark:bg-dark-700"
|
||||
:disabled="verifying"
|
||||
@input="handleCodeInput($event, index)"
|
||||
@keydown="handleKeydown($event, index)"
|
||||
@paste="handlePaste"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="verifying" class="mt-3 flex items-center justify-center gap-2 text-sm text-gray-500">
|
||||
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-primary-500"></div>
|
||||
{{ t('common.verifying') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary w-full"
|
||||
:disabled="verifying"
|
||||
@click="handleCancel"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { totpAPI } from '@/api'
|
||||
import type { StepUpController } from '@/composables/useStepUp'
|
||||
|
||||
const props = defineProps<{
|
||||
controller: StepUpController
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const verifying = ref(false)
|
||||
const code = ref<string[]>(['', '', '', '', '', ''])
|
||||
const inputRefs = ref<(HTMLInputElement | null)[]>([])
|
||||
const hiddenOtpInputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
// Focus the first cell whenever the dialog opens.
|
||||
watch(
|
||||
() => props.controller.visible.value,
|
||||
(open) => {
|
||||
if (open) {
|
||||
resetInputs()
|
||||
nextTick(() => inputRefs.value[0]?.focus())
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Auto-submit once 6 digits are entered.
|
||||
watch(
|
||||
() => code.value.join(''),
|
||||
(newCode) => {
|
||||
if (newCode.length === 6 && !verifying.value) {
|
||||
submit(newCode)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function submit(otp: string) {
|
||||
verifying.value = true
|
||||
try {
|
||||
await totpAPI.stepUp(otp)
|
||||
verifying.value = false
|
||||
props.controller.onVerified()
|
||||
} catch (err: any) {
|
||||
verifying.value = false
|
||||
appStore.showError(err?.message || t('stepUp.verifyFailed'))
|
||||
resetInputs()
|
||||
nextTick(() => inputRefs.value[0]?.focus())
|
||||
}
|
||||
}
|
||||
|
||||
function resetInputs() {
|
||||
code.value = ['', '', '', '', '', '']
|
||||
inputRefs.value.forEach((input) => {
|
||||
if (input) input.value = ''
|
||||
})
|
||||
if (hiddenOtpInputRef.value) hiddenOtpInputRef.value.value = ''
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
if (verifying.value) return
|
||||
props.controller.onCancel()
|
||||
}
|
||||
|
||||
const setInputRef = (el: any, index: number) => {
|
||||
inputRefs.value[index] = el as HTMLInputElement | null
|
||||
}
|
||||
|
||||
const handleCodeInput = (event: Event, index: number) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
const value = input.value.replace(/[^0-9]/g, '')
|
||||
code.value[index] = value
|
||||
if (value && index < 5) {
|
||||
nextTick(() => inputRefs.value[index + 1]?.focus())
|
||||
}
|
||||
}
|
||||
|
||||
const handleHiddenOtpInput = (event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
const digits = input.value.replace(/[^0-9]/g, '').slice(0, 6).split('')
|
||||
for (let i = 0; i < 6; i++) {
|
||||
code.value[i] = digits[i] || ''
|
||||
if (inputRefs.value[i]) inputRefs.value[i]!.value = digits[i] || ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeydown = (event: KeyboardEvent, index: number) => {
|
||||
if (event.key === 'Backspace') {
|
||||
const input = event.target as HTMLInputElement
|
||||
if (!input.value && index > 0) {
|
||||
event.preventDefault()
|
||||
inputRefs.value[index - 1]?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = (event: ClipboardEvent) => {
|
||||
event.preventDefault()
|
||||
const pastedData = event.clipboardData?.getData('text') || ''
|
||||
const digits = pastedData.replace(/[^0-9]/g, '').slice(0, 6).split('')
|
||||
for (let i = 0; i < 6; i++) {
|
||||
code.value[i] = digits[i] || ''
|
||||
if (inputRefs.value[i]) inputRefs.value[i]!.value = digits[i] || ''
|
||||
}
|
||||
const focusIndex = Math.min(digits.length, 5)
|
||||
nextTick(() => inputRefs.value[focusIndex]?.focus())
|
||||
}
|
||||
</script>
|
||||
@@ -800,7 +800,8 @@ const adminNavItems = computed((): NavItem[] => {
|
||||
{ path: '/admin/orders/plans', label: t('nav.paymentPlans'), icon: CreditCardIcon },
|
||||
],
|
||||
},
|
||||
{ path: '/admin/usage', label: t('nav.usage'), icon: ChartIcon }
|
||||
{ path: '/admin/usage', label: t('nav.usage'), icon: ChartIcon },
|
||||
{ path: '/admin/audit-logs', label: t('nav.auditLogs'), icon: ShieldIcon, hideInSimpleMode: true }
|
||||
]
|
||||
|
||||
const visible = applyFeatureFlags(baseItems)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { useStepUp, isStepUpRequired, isStepUpBlocked, stepUpBlockReason } from '../useStepUp'
|
||||
|
||||
describe('useStepUp error classification', () => {
|
||||
it('detects STEP_UP_REQUIRED from code field', () => {
|
||||
expect(isStepUpRequired({ status: 403, code: 'STEP_UP_REQUIRED' })).toBe(true)
|
||||
expect(isStepUpRequired({ status: 403, reason: 'STEP_UP_REQUIRED' })).toBe(true)
|
||||
expect(isStepUpRequired({ status: 500, code: 'INTERNAL' })).toBe(false)
|
||||
expect(isStepUpRequired(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('detects blocked (non-retryable) step-up errors', () => {
|
||||
expect(isStepUpBlocked({ code: 'STEP_UP_TOTP_NOT_ENABLED' })).toBe(true)
|
||||
expect(isStepUpBlocked({ reason: 'STEP_UP_ADMIN_API_KEY_FORBIDDEN' })).toBe(true)
|
||||
expect(isStepUpBlocked({ code: 'STEP_UP_REQUIRED' })).toBe(false)
|
||||
})
|
||||
|
||||
it('surfaces the block reason marker', () => {
|
||||
expect(stepUpBlockReason({ reason: 'STEP_UP_ADMIN_API_KEY_FORBIDDEN' })).toBe('STEP_UP_ADMIN_API_KEY_FORBIDDEN')
|
||||
expect(stepUpBlockReason({ code: 'OTHER' })).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useStepUp.run', () => {
|
||||
it('returns the action result directly on success', async () => {
|
||||
const stepUp = useStepUp()
|
||||
const result = await stepUp.run(async () => 42)
|
||||
expect(result).toBe(42)
|
||||
expect(stepUp.visible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('re-throws non-step-up errors without prompting', async () => {
|
||||
const stepUp = useStepUp()
|
||||
const err = { status: 500, code: 'INTERNAL' }
|
||||
await expect(stepUp.run(async () => { throw err })).rejects.toBe(err)
|
||||
expect(stepUp.visible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('re-throws blocked errors without prompting', async () => {
|
||||
const stepUp = useStepUp()
|
||||
const err = { status: 403, code: 'STEP_UP_TOTP_NOT_ENABLED' }
|
||||
await expect(stepUp.run(async () => { throw err })).rejects.toBe(err)
|
||||
expect(stepUp.visible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('prompts on STEP_UP_REQUIRED and retries after verification', async () => {
|
||||
const stepUp = useStepUp()
|
||||
let calls = 0
|
||||
const action = async () => {
|
||||
calls++
|
||||
if (calls === 1) throw { status: 403, code: 'STEP_UP_REQUIRED' }
|
||||
return 'ok'
|
||||
}
|
||||
const promise = stepUp.run(action)
|
||||
// The dialog should now be open, awaiting verification (after the first rejection is handled).
|
||||
await vi.waitFor(() => expect(stepUp.visible.value).toBe(true))
|
||||
stepUp.onVerified()
|
||||
await expect(promise).resolves.toBe('ok')
|
||||
expect(calls).toBe(2)
|
||||
expect(stepUp.visible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('re-throws the original error if the user cancels the prompt', async () => {
|
||||
const stepUp = useStepUp()
|
||||
const err = { status: 403, code: 'STEP_UP_REQUIRED' }
|
||||
const promise = stepUp.run(async () => { throw err })
|
||||
await vi.waitFor(() => expect(stepUp.visible.value).toBe(true))
|
||||
stepUp.onCancel()
|
||||
await expect(promise).rejects.toBe(err)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Step-up (sudo) 2FA composable.
|
||||
*
|
||||
* Wraps a sensitive admin action so that when the backend responds with a
|
||||
* STEP_UP_REQUIRED error, the caller can prompt for a TOTP code, obtain a
|
||||
* short-lived grant, and transparently retry the original action.
|
||||
*
|
||||
* Usage in a view:
|
||||
* const stepUp = useStepUp()
|
||||
* async function exportData() {
|
||||
* await stepUp.run(() => adminAPI.accounts.exportData(...))
|
||||
* }
|
||||
* // template: <TotpStepUpDialog :controller="stepUp" />
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
|
||||
/** Error codes the backend uses to signal step-up state. */
|
||||
const STEP_UP_REQUIRED = 'STEP_UP_REQUIRED'
|
||||
const STEP_UP_TOTP_NOT_ENABLED = 'STEP_UP_TOTP_NOT_ENABLED'
|
||||
const STEP_UP_ADMIN_API_KEY_FORBIDDEN = 'STEP_UP_ADMIN_API_KEY_FORBIDDEN'
|
||||
|
||||
interface ApiError {
|
||||
status?: number
|
||||
code?: string | number
|
||||
reason?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** Extract the semantic error marker from either envelope shape (code or reason). */
|
||||
function markerOf(err: unknown): string {
|
||||
const e = (err ?? {}) as ApiError
|
||||
const candidates = [e.code, e.reason].map((v) => (typeof v === 'string' ? v : ''))
|
||||
return candidates.find((v) => v.startsWith('STEP_UP')) || ''
|
||||
}
|
||||
|
||||
export function isStepUpRequired(err: unknown): boolean {
|
||||
return markerOf(err) === STEP_UP_REQUIRED
|
||||
}
|
||||
|
||||
export function isStepUpBlocked(err: unknown): boolean {
|
||||
const m = markerOf(err)
|
||||
return m === STEP_UP_TOTP_NOT_ENABLED || m === STEP_UP_ADMIN_API_KEY_FORBIDDEN
|
||||
}
|
||||
|
||||
export function stepUpBlockReason(err: unknown): string {
|
||||
return markerOf(err)
|
||||
}
|
||||
|
||||
export type StepUpController = ReturnType<typeof useStepUp>
|
||||
|
||||
export function useStepUp() {
|
||||
const visible = ref(false)
|
||||
const blockedReason = ref<string>('')
|
||||
let resolver: ((ok: boolean) => void) | null = null
|
||||
|
||||
/** Open the TOTP dialog and resolve true once a grant is obtained. */
|
||||
function prompt(): Promise<boolean> {
|
||||
visible.value = true
|
||||
return new Promise<boolean>((resolve) => {
|
||||
resolver = resolve
|
||||
})
|
||||
}
|
||||
|
||||
function onVerified() {
|
||||
visible.value = false
|
||||
resolver?.(true)
|
||||
resolver = null
|
||||
}
|
||||
|
||||
function onCancel() {
|
||||
visible.value = false
|
||||
resolver?.(false)
|
||||
resolver = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a sensitive action. On STEP_UP_REQUIRED, prompt for a TOTP code and
|
||||
* retry once. STEP_UP_TOTP_NOT_ENABLED / admin-api-key errors are surfaced
|
||||
* to the caller (they cannot be resolved by entering a code).
|
||||
*/
|
||||
async function run<T>(action: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await action()
|
||||
} catch (err) {
|
||||
if (isStepUpBlocked(err)) {
|
||||
blockedReason.value = markerOf(err)
|
||||
throw err
|
||||
}
|
||||
if (!isStepUpRequired(err)) {
|
||||
throw err
|
||||
}
|
||||
const ok = await prompt()
|
||||
if (!ok) {
|
||||
throw err
|
||||
}
|
||||
// Retry once now that the session holds a step-up grant.
|
||||
return await action()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
blockedReason,
|
||||
prompt,
|
||||
onVerified,
|
||||
onCancel,
|
||||
run
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export default {
|
||||
audit: {
|
||||
title: 'Audit Logs',
|
||||
description: 'Records management-plane operations by admins and users. Header credentials keep only their first/last characters and request bodies are redacted. Entries cannot be deleted individually; clearing all requires two-factor verification.',
|
||||
clearAll: 'Clear All',
|
||||
empty: 'No audit logs yet',
|
||||
loadFailed: 'Failed to load audit logs',
|
||||
filters: {
|
||||
all: 'All',
|
||||
q: 'Keyword',
|
||||
qPlaceholder: 'Path / action / actor email',
|
||||
actorEmail: 'Actor Email',
|
||||
action: 'Action',
|
||||
clientIp: 'Client IP',
|
||||
method: 'Method',
|
||||
authMethod: 'Auth Method',
|
||||
result: 'Result',
|
||||
resultSuccess: 'Success',
|
||||
resultFailure: 'Failure',
|
||||
startTime: 'Start Time',
|
||||
endTime: 'End Time'
|
||||
},
|
||||
columns: {
|
||||
time: 'Time',
|
||||
actor: 'Actor',
|
||||
action: 'Action',
|
||||
method: 'Method',
|
||||
result: 'Result',
|
||||
clientIp: 'Client IP',
|
||||
detail: 'Detail'
|
||||
},
|
||||
detail: {
|
||||
title: 'Audit Log Detail',
|
||||
actorRole: 'Role',
|
||||
methodPath: 'Method / Path',
|
||||
latency: 'Latency',
|
||||
requestId: 'Request ID',
|
||||
credential: 'Credential (masked)',
|
||||
userAgent: 'User-Agent',
|
||||
requestBody: 'Request Body (redacted)',
|
||||
extra: 'Extra'
|
||||
},
|
||||
clearConfirm: {
|
||||
title: 'Clear All Audit Logs',
|
||||
message: 'This permanently deletes all audit logs and cannot be undone. The clear action itself is recorded. Continue?',
|
||||
totpTitle: 'Enter Two-Factor Code',
|
||||
totpHint: 'Clearing audit logs requires a fresh TOTP verification.',
|
||||
success: 'Cleared {count} audit log(s)',
|
||||
failed: 'Failed to clear audit logs'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import accounts from './accounts'
|
||||
import resources from './resources'
|
||||
import ops from './ops'
|
||||
import settings from './settings'
|
||||
import audit from './audit'
|
||||
|
||||
export default {
|
||||
...overview,
|
||||
@@ -12,4 +13,5 @@ export default {
|
||||
...resources,
|
||||
...ops,
|
||||
...settings,
|
||||
...audit,
|
||||
}
|
||||
@@ -126,6 +126,12 @@ export default {
|
||||
totpKeyNotConfigured:
|
||||
'Please configure TOTP_ENCRYPTION_KEY in environment variables first. Generate a key with: openssl rand -hex 32'
|
||||
},
|
||||
security: {
|
||||
sessionBinding: 'Session IP/UA Binding',
|
||||
sessionBindingHint: 'Bind login sessions to the client IP and User-Agent. Any change immediately invalidates the session and forces re-login, raising the bar for stolen-credential reuse.',
|
||||
auditRetention: 'Audit Log Retention (days)',
|
||||
auditRetentionHint: 'Audit logs older than this are cleaned up automatically. Set to 0 to keep them forever (manual clear only).'
|
||||
},
|
||||
turnstile: {
|
||||
title: 'Cloudflare Turnstile',
|
||||
description: 'Bot protection for login and registration',
|
||||
|
||||
@@ -190,6 +190,7 @@ export default {
|
||||
channelMonitor: 'Channel Monitor',
|
||||
channelStatus: 'Channel Status',
|
||||
riskControl: 'Risk Control',
|
||||
auditLogs: 'Audit Logs',
|
||||
},
|
||||
|
||||
// Auth
|
||||
@@ -413,5 +414,14 @@ export default {
|
||||
invalidOrExpiredToken: 'The password reset link is invalid or has expired. Please request a new one.'
|
||||
},
|
||||
|
||||
// Step-up (sudo) 2FA prompt
|
||||
stepUp: {
|
||||
title: 'Two-Factor Verification Required',
|
||||
hint: 'Enter the 6-digit code from your authenticator app to continue this sensitive operation.',
|
||||
verifyFailed: 'Verification failed, please try again',
|
||||
notEnabled: 'This operation requires two-factor authentication. Please enable TOTP in your profile first.',
|
||||
adminApiKeyForbidden: 'Admin API keys cannot perform this operation. Use a two-factor verified admin session.'
|
||||
},
|
||||
|
||||
// Dashboard
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export default {
|
||||
audit: {
|
||||
title: '操作日志',
|
||||
description: '记录管理员与用户的管理面操作,请求头凭证仅保留首尾、请求体已脱敏。日志无法单条删除,全量清理需二次验证。',
|
||||
clearAll: '全部清理',
|
||||
empty: '暂无操作日志',
|
||||
loadFailed: '加载操作日志失败',
|
||||
filters: {
|
||||
all: '全部',
|
||||
q: '关键字',
|
||||
qPlaceholder: '路径 / 动作 / 操作者邮箱',
|
||||
actorEmail: '操作者邮箱',
|
||||
action: '动作',
|
||||
clientIp: '客户端 IP',
|
||||
method: '请求方法',
|
||||
authMethod: '认证方式',
|
||||
result: '结果',
|
||||
resultSuccess: '成功',
|
||||
resultFailure: '失败',
|
||||
startTime: '开始时间',
|
||||
endTime: '结束时间'
|
||||
},
|
||||
columns: {
|
||||
time: '时间',
|
||||
actor: '操作者',
|
||||
action: '动作',
|
||||
method: '方法',
|
||||
result: '结果',
|
||||
clientIp: '客户端 IP',
|
||||
detail: '详情'
|
||||
},
|
||||
detail: {
|
||||
title: '操作日志详情',
|
||||
actorRole: '角色',
|
||||
methodPath: '方法 / 路径',
|
||||
latency: '耗时',
|
||||
requestId: '请求 ID',
|
||||
credential: '凭证(掩码)',
|
||||
userAgent: 'User-Agent',
|
||||
requestBody: '请求体(已脱敏)',
|
||||
extra: '附加信息'
|
||||
},
|
||||
clearConfirm: {
|
||||
title: '清理全部操作日志',
|
||||
message: '此操作将永久删除所有操作日志,且不可恢复。清理动作本身会被留痕记录。确定继续吗?',
|
||||
totpTitle: '输入二次验证码',
|
||||
totpHint: '清理操作日志需要现场验证 TOTP 验证码。',
|
||||
success: '已清理 {count} 条操作日志',
|
||||
failed: '清理操作日志失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import accounts from './accounts'
|
||||
import resources from './resources'
|
||||
import ops from './ops'
|
||||
import settings from './settings'
|
||||
import audit from './audit'
|
||||
|
||||
export default {
|
||||
...overview,
|
||||
@@ -12,4 +13,5 @@ export default {
|
||||
...resources,
|
||||
...ops,
|
||||
...settings,
|
||||
...audit,
|
||||
}
|
||||
@@ -126,6 +126,12 @@ export default {
|
||||
totpKeyNotConfigured:
|
||||
'请先在环境变量中配置 TOTP_ENCRYPTION_KEY。使用命令 openssl rand -hex 32 生成密钥。'
|
||||
},
|
||||
security: {
|
||||
sessionBinding: '会话 IP/UA 绑定',
|
||||
sessionBindingHint: '将登录会话与客户端 IP 和 User-Agent 绑定,任一变化即强制该会话失效并需重新登录(提升被盗凭证的利用门槛)。',
|
||||
auditRetention: '操作日志保留天数',
|
||||
auditRetentionHint: '超过该天数的操作日志将被自动清理;填 0 表示永久保留(仅支持手动清空)。'
|
||||
},
|
||||
turnstile: {
|
||||
title: 'Cloudflare Turnstile',
|
||||
description: '登录和注册的机器人防护',
|
||||
|
||||
@@ -190,6 +190,7 @@ export default {
|
||||
channelMonitor: '渠道监控',
|
||||
channelStatus: '渠道状态',
|
||||
riskControl: '风控中心',
|
||||
auditLogs: '操作日志',
|
||||
},
|
||||
|
||||
// Auth
|
||||
@@ -412,5 +413,14 @@ export default {
|
||||
invalidOrExpiredToken: '密码重置链接无效或已过期。请重新请求一个新链接。'
|
||||
},
|
||||
|
||||
// Step-up(敏感操作二次验证)
|
||||
stepUp: {
|
||||
title: '需要二次验证',
|
||||
hint: '请输入身份验证器应用中的 6 位验证码以继续此敏感操作。',
|
||||
verifyFailed: '验证失败,请重试',
|
||||
notEnabled: '此操作需要开启二次验证,请先在个人资料中启用 TOTP。',
|
||||
adminApiKeyForbidden: '管理 API Key 无法执行此操作,请使用已通过二次验证的管理员会话。'
|
||||
},
|
||||
|
||||
// Dashboard
|
||||
}
|
||||
@@ -415,6 +415,18 @@ const routes: RouteRecordRaw[] = [
|
||||
descriptionKey: 'admin.ops.description'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: '/admin/audit-logs',
|
||||
name: 'AdminAuditLogs',
|
||||
component: () => import('@/views/admin/AuditLogView.vue'),
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
requiresAdmin: true,
|
||||
title: 'Audit Logs',
|
||||
titleKey: 'admin.audit.title',
|
||||
descriptionKey: 'admin.audit.description'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: '/admin/users',
|
||||
name: 'AdminUsers',
|
||||
|
||||
@@ -475,6 +475,7 @@
|
||||
</ConfirmDialog>
|
||||
<ErrorPassthroughRulesModal :show="showErrorPassthrough" @close="showErrorPassthrough = false" />
|
||||
<TLSFingerprintProfilesModal :show="showTLSFingerprintProfiles" @close="showTLSFingerprintProfiles = false" />
|
||||
<TotpStepUpDialog :controller="accountExportStepUp" />
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
@@ -488,6 +489,8 @@ import { adminAPI } from '@/api/admin'
|
||||
import { useTableLoader } from '@/composables/useTableLoader'
|
||||
import { useSwipeSelect, type SwipeSelectVirtualContext } from '@/composables/useSwipeSelect'
|
||||
import { useTableSelection } from '@/composables/useTableSelection'
|
||||
import { useStepUp, isStepUpBlocked, stepUpBlockReason } from '@/composables/useStepUp'
|
||||
import TotpStepUpDialog from '@/components/auth/TotpStepUpDialog.vue'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import TablePageLayout from '@/components/layout/TablePageLayout.vue'
|
||||
import DataTable from '@/components/common/DataTable.vue'
|
||||
@@ -1797,14 +1800,14 @@ const handleExportData = async () => {
|
||||
if (exportingData.value) return
|
||||
exportingData.value = true
|
||||
try {
|
||||
const dataPayload = await adminAPI.accounts.exportData(
|
||||
const dataPayload = await accountExportStepUp.run(() => adminAPI.accounts.exportData(
|
||||
selIds.value.length > 0
|
||||
? { ids: selIds.value, includeProxies: includeProxyOnExport.value }
|
||||
: {
|
||||
includeProxies: includeProxyOnExport.value,
|
||||
filters: buildAccountQueryFilters()
|
||||
}
|
||||
)
|
||||
))
|
||||
const timestamp = formatExportTimestamp()
|
||||
const filename = `sub2api-account-${timestamp}.json`
|
||||
const blob = new Blob([JSON.stringify(dataPayload, null, 2)], { type: 'application/json' })
|
||||
@@ -1822,12 +1825,21 @@ const handleExportData = async () => {
|
||||
appStore.showSuccess(t('admin.accounts.dataExported'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
appStore.showError(error?.message || t('admin.accounts.dataExportFailed'))
|
||||
if (isStepUpBlocked(error)) {
|
||||
appStore.showError(
|
||||
stepUpBlockReason(error) === 'STEP_UP_ADMIN_API_KEY_FORBIDDEN'
|
||||
? t('stepUp.adminApiKeyForbidden')
|
||||
: t('stepUp.notEnabled')
|
||||
)
|
||||
} else {
|
||||
appStore.showError(error?.message || t('admin.accounts.dataExportFailed'))
|
||||
}
|
||||
} finally {
|
||||
exportingData.value = false
|
||||
showExportDataDialog.value = false
|
||||
}
|
||||
}
|
||||
const accountExportStepUp = useStepUp()
|
||||
const closeTestModal = () => { showTest.value = false; testingAcc.value = null }
|
||||
const closeStatsModal = () => { showStats.value = false; statsAcc.value = null }
|
||||
const closeReAuthModal = () => { showReAuth.value = false; reAuthAcc.value = null }
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Page header -->
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold text-gray-900 dark:text-white">{{ t('admin.audit.title') }}</h1>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">{{ t('admin.audit.description') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn btn-danger btn-sm" @click="openClearDialog">
|
||||
{{ t('admin.audit.clearAll') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Filters -->
|
||||
<div class="card p-4">
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.q') }}</span>
|
||||
<input v-model.trim="filters.q" class="input" :placeholder="t('admin.audit.filters.qPlaceholder')" @keyup.enter="search" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.actorEmail') }}</span>
|
||||
<input v-model.trim="filters.actor_email" class="input" @keyup.enter="search" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.action') }}</span>
|
||||
<input v-model.trim="filters.action" class="input" @keyup.enter="search" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.clientIp') }}</span>
|
||||
<input v-model.trim="filters.client_ip" class="input" @keyup.enter="search" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.method') }}</span>
|
||||
<Select v-model="filters.method" :options="methodOptions" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.authMethod') }}</span>
|
||||
<Select v-model="filters.auth_method" :options="authMethodOptions" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.result') }}</span>
|
||||
<Select v-model="filters.success" :options="resultOptions" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.startTime') }}</span>
|
||||
<input v-model="filters.start_time" type="datetime-local" class="input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.audit.filters.endTime') }}</span>
|
||||
<input v-model="filters.end_time" type="datetime-local" class="input" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="mt-3 flex gap-2">
|
||||
<button type="button" class="btn btn-primary btn-sm" :disabled="loading" @click="search">
|
||||
{{ t('common.search') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" :disabled="loading" @click="resetFilters">
|
||||
{{ t('common.reset') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Table -->
|
||||
<div class="card overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full divide-y divide-gray-200 dark:divide-dark-700">
|
||||
<thead class="bg-gray-50 dark:bg-dark-900/40">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.time') }}</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.actor') }}</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.action') }}</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.method') }}</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.result') }}</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.clientIp') }}</th>
|
||||
<th class="px-4 py-3 text-right text-xs font-medium uppercase text-gray-500">{{ t('admin.audit.columns.detail') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200 dark:divide-dark-700">
|
||||
<tr v-if="loading">
|
||||
<td colspan="7" class="px-4 py-8 text-center text-sm text-gray-500">{{ t('common.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="logs.length === 0">
|
||||
<td colspan="7" class="px-4 py-8 text-center text-sm text-gray-500">{{ t('admin.audit.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="log in logs" :key="log.id" class="hover:bg-gray-50 dark:hover:bg-dark-800/60">
|
||||
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{{ formatTime(log.created_at) }}</td>
|
||||
<td class="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
|
||||
<div class="font-medium">{{ log.actor_email || '—' }}</div>
|
||||
<div class="text-xs text-gray-400">{{ log.actor_role }}<span v-if="log.auth_method"> · {{ log.auth_method }}</span></div>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-sm font-mono text-gray-700 dark:text-gray-300">{{ log.action }}</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-500">{{ log.method }}</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 text-sm">
|
||||
<span :class="statusBadgeClass(log.status_code)">{{ log.status_code }}</span>
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-500">{{ log.client_ip || '—' }}</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 text-right text-sm">
|
||||
<button type="button" class="text-primary-600 hover:underline dark:text-primary-400" @click="openDetail(log.id)">
|
||||
{{ t('admin.audit.columns.detail') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="border-t border-gray-200 px-4 py-3 dark:border-dark-700">
|
||||
<Pagination
|
||||
:total="total"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
@update:page="onPageChange"
|
||||
@update:pageSize="onPageSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Detail dialog -->
|
||||
<BaseDialog :show="detailVisible" :title="t('admin.audit.detail.title')" width="wide" @close="detailVisible = false">
|
||||
<div v-if="detailLoading" class="py-8 text-center text-sm text-gray-500">{{ t('common.loading') }}</div>
|
||||
<div v-else-if="detail" class="space-y-3 text-sm">
|
||||
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<DetailRow :label="t('admin.audit.columns.time')" :value="formatTime(detail.created_at)" />
|
||||
<DetailRow :label="t('admin.audit.columns.actor')" :value="detail.actor_email || '—'" />
|
||||
<DetailRow :label="t('admin.audit.detail.actorRole')" :value="detail.actor_role" />
|
||||
<DetailRow :label="t('admin.audit.filters.authMethod')" :value="detail.auth_method" />
|
||||
<DetailRow :label="t('admin.audit.columns.action')" :value="detail.action" mono />
|
||||
<DetailRow :label="t('admin.audit.detail.methodPath')" :value="`${detail.method} ${detail.path}`" mono />
|
||||
<DetailRow :label="t('admin.audit.columns.result')" :value="String(detail.status_code)" />
|
||||
<DetailRow :label="t('admin.audit.detail.latency')" :value="`${detail.latency_ms} ms`" />
|
||||
<DetailRow :label="t('admin.audit.columns.clientIp')" :value="detail.client_ip || '—'" />
|
||||
<DetailRow :label="t('admin.audit.detail.requestId')" :value="detail.request_id || '—'" mono />
|
||||
<DetailRow :label="t('admin.audit.detail.credential')" :value="detail.credential_masked || '—'" mono />
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs font-medium text-gray-500">{{ t('admin.audit.detail.userAgent') }}</div>
|
||||
<div class="break-all rounded bg-gray-50 p-2 font-mono text-xs text-gray-600 dark:bg-dark-900/40 dark:text-gray-400">{{ detail.user_agent || '—' }}</div>
|
||||
</div>
|
||||
<div v-if="detail.request_body">
|
||||
<div class="mb-1 text-xs font-medium text-gray-500">{{ t('admin.audit.detail.requestBody') }}</div>
|
||||
<pre class="max-h-72 overflow-auto rounded bg-gray-50 p-3 font-mono text-xs text-gray-600 dark:bg-dark-900/40 dark:text-gray-400">{{ prettyBody(detail.request_body) }}</pre>
|
||||
</div>
|
||||
<div v-if="detail.extra && Object.keys(detail.extra).length">
|
||||
<div class="mb-1 text-xs font-medium text-gray-500">{{ t('admin.audit.detail.extra') }}</div>
|
||||
<pre class="max-h-48 overflow-auto rounded bg-gray-50 p-3 font-mono text-xs text-gray-600 dark:bg-dark-900/40 dark:text-gray-400">{{ JSON.stringify(detail.extra, null, 2) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
|
||||
<!-- Clear confirmation → step-up TOTP -->
|
||||
<ConfirmDialog
|
||||
:show="clearConfirmVisible"
|
||||
:title="t('admin.audit.clearConfirm.title')"
|
||||
:message="t('admin.audit.clearConfirm.message')"
|
||||
:confirm-text="t('admin.audit.clearAll')"
|
||||
:cancel-text="t('common.cancel')"
|
||||
danger
|
||||
@confirm="onClearConfirmed"
|
||||
@cancel="clearConfirmVisible = false"
|
||||
/>
|
||||
|
||||
<!-- Reused: TOTP prompt for the clear operation -->
|
||||
<div v-if="clearTotpVisible" class="fixed inset-0 z-[60] overflow-y-auto">
|
||||
<div class="flex min-h-full items-center justify-center p-4">
|
||||
<div class="fixed inset-0 bg-black/50" @click="cancelClearTotp"></div>
|
||||
<div class="relative w-full max-w-md rounded-xl bg-white p-6 shadow-xl dark:bg-dark-800">
|
||||
<h3 class="mb-2 text-center text-lg font-semibold text-gray-900 dark:text-white">{{ t('admin.audit.clearConfirm.totpTitle') }}</h3>
|
||||
<p class="mb-4 text-center text-sm text-gray-500 dark:text-gray-400">{{ t('admin.audit.clearConfirm.totpHint') }}</p>
|
||||
<input
|
||||
v-model.trim="clearTotpCode"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
maxlength="6"
|
||||
autocomplete="one-time-code"
|
||||
class="input mb-4 text-center text-lg tracking-[0.5em]"
|
||||
placeholder="••••••"
|
||||
@keyup.enter="submitClear"
|
||||
/>
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="btn btn-secondary flex-1" :disabled="clearing" @click="cancelClearTotp">{{ t('common.cancel') }}</button>
|
||||
<button type="button" class="btn btn-danger flex-1" :disabled="clearing || clearTotpCode.length !== 6" @click="submitClear">
|
||||
{{ clearing ? t('common.loading') : t('admin.audit.clearAll') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { adminAPI, type AuditLog } from '@/api/admin'
|
||||
import Pagination from '@/components/common/Pagination.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import BaseDialog from '@/components/common/BaseDialog.vue'
|
||||
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
|
||||
import { useAppStore } from '@/stores'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
|
||||
// Tiny inline label/value row for the detail dialog.
|
||||
const DetailRow = (props: { label: string; value: string; mono?: boolean }) =>
|
||||
h('div', { class: 'flex flex-col gap-0.5' }, [
|
||||
h('span', { class: 'text-xs text-gray-400' }, props.label),
|
||||
h('span', { class: ['text-gray-700 dark:text-gray-200 break-all', props.mono ? 'font-mono text-xs' : ''] }, props.value)
|
||||
])
|
||||
|
||||
const loading = ref(false)
|
||||
const logs = ref<AuditLog[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
|
||||
const filters = reactive({
|
||||
q: '',
|
||||
actor_email: '',
|
||||
action: '',
|
||||
client_ip: '',
|
||||
method: '',
|
||||
auth_method: '',
|
||||
success: '',
|
||||
start_time: '',
|
||||
end_time: ''
|
||||
})
|
||||
|
||||
const methodOptions = computed(() => [
|
||||
{ value: '', label: t('admin.audit.filters.all') },
|
||||
{ value: 'POST', label: 'POST' },
|
||||
{ value: 'PUT', label: 'PUT' },
|
||||
{ value: 'PATCH', label: 'PATCH' },
|
||||
{ value: 'DELETE', label: 'DELETE' },
|
||||
{ value: 'GET', label: 'GET' }
|
||||
])
|
||||
|
||||
const authMethodOptions = computed(() => [
|
||||
{ value: '', label: t('admin.audit.filters.all') },
|
||||
{ value: 'jwt', label: 'JWT' },
|
||||
{ value: 'admin_api_key', label: 'Admin API Key' }
|
||||
])
|
||||
|
||||
const resultOptions = computed(() => [
|
||||
{ value: '', label: t('admin.audit.filters.all') },
|
||||
{ value: 'true', label: t('admin.audit.filters.resultSuccess') },
|
||||
{ value: 'false', label: t('admin.audit.filters.resultFailure') }
|
||||
])
|
||||
|
||||
function toRFC3339(local: string): string | undefined {
|
||||
if (!local) return undefined
|
||||
const d = new Date(local)
|
||||
if (Number.isNaN(d.getTime())) return undefined
|
||||
return d.toISOString()
|
||||
}
|
||||
|
||||
function buildQuery() {
|
||||
return {
|
||||
page: page.value,
|
||||
page_size: pageSize.value,
|
||||
q: filters.q || undefined,
|
||||
actor_email: filters.actor_email || undefined,
|
||||
action: filters.action || undefined,
|
||||
client_ip: filters.client_ip || undefined,
|
||||
method: filters.method || undefined,
|
||||
auth_method: filters.auth_method || undefined,
|
||||
success: filters.success || undefined,
|
||||
start_time: toRFC3339(filters.start_time),
|
||||
end_time: toRFC3339(filters.end_time)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchLogs() {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await adminAPI.audit.list(buildQuery())
|
||||
logs.value = res.items
|
||||
total.value = res.total
|
||||
} catch (err: any) {
|
||||
appStore.showError(err?.message || t('admin.audit.loadFailed'))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
page.value = 1
|
||||
fetchLogs()
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.q = ''
|
||||
filters.actor_email = ''
|
||||
filters.action = ''
|
||||
filters.client_ip = ''
|
||||
filters.method = ''
|
||||
filters.auth_method = ''
|
||||
filters.success = ''
|
||||
filters.start_time = ''
|
||||
filters.end_time = ''
|
||||
search()
|
||||
}
|
||||
|
||||
function onPageChange(p: number) {
|
||||
page.value = p
|
||||
fetchLogs()
|
||||
}
|
||||
|
||||
function onPageSizeChange(ps: number) {
|
||||
pageSize.value = ps
|
||||
page.value = 1
|
||||
fetchLogs()
|
||||
}
|
||||
|
||||
// Detail dialog
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<AuditLog | null>(null)
|
||||
|
||||
async function openDetail(id: number) {
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
detail.value = null
|
||||
try {
|
||||
detail.value = await adminAPI.audit.get(id)
|
||||
} catch (err: any) {
|
||||
appStore.showError(err?.message || t('admin.audit.loadFailed'))
|
||||
detailVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function prettyBody(body: string): string {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(body), null, 2)
|
||||
} catch {
|
||||
return body
|
||||
}
|
||||
}
|
||||
|
||||
// Clear-all flow: confirm → TOTP → clear
|
||||
const clearConfirmVisible = ref(false)
|
||||
const clearTotpVisible = ref(false)
|
||||
const clearTotpCode = ref('')
|
||||
const clearing = ref(false)
|
||||
|
||||
function openClearDialog() {
|
||||
clearConfirmVisible.value = true
|
||||
}
|
||||
|
||||
function onClearConfirmed() {
|
||||
clearConfirmVisible.value = false
|
||||
clearTotpCode.value = ''
|
||||
clearTotpVisible.value = true
|
||||
}
|
||||
|
||||
function cancelClearTotp() {
|
||||
if (clearing.value) return
|
||||
clearTotpVisible.value = false
|
||||
}
|
||||
|
||||
async function submitClear() {
|
||||
if (clearTotpCode.value.length !== 6) return
|
||||
clearing.value = true
|
||||
try {
|
||||
const res = await adminAPI.audit.clear(clearTotpCode.value)
|
||||
clearTotpVisible.value = false
|
||||
appStore.showSuccess(t('admin.audit.clearConfirm.success', { count: res.deleted }))
|
||||
search()
|
||||
} catch (err: any) {
|
||||
appStore.showError(err?.message || t('admin.audit.clearConfirm.failed'))
|
||||
clearTotpCode.value = ''
|
||||
} finally {
|
||||
clearing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Helpers
|
||||
function formatTime(iso: string): string {
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return iso
|
||||
return d.toLocaleString()
|
||||
}
|
||||
|
||||
function statusBadgeClass(status: number): string {
|
||||
const base = 'inline-flex rounded-full px-2 py-0.5 text-xs font-medium '
|
||||
if (status >= 500) return base + 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'
|
||||
if (status >= 400) return base + 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
|
||||
return base + 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
|
||||
}
|
||||
|
||||
onMounted(fetchLogs)
|
||||
</script>
|
||||
@@ -276,6 +276,7 @@
|
||||
</div>
|
||||
</transition>
|
||||
</teleport>
|
||||
<TotpStepUpDialog :controller="backupStepUp" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
@@ -284,9 +285,23 @@ import { useI18n } from 'vue-i18n'
|
||||
import { adminAPI } from '@/api'
|
||||
import { useAppStore } from '@/stores'
|
||||
import type { BackupS3Config, BackupScheduleConfig, BackupRecord } from '@/api/admin/backup'
|
||||
import { useStepUp, isStepUpBlocked, stepUpBlockReason } from '@/composables/useStepUp'
|
||||
import TotpStepUpDialog from '@/components/auth/TotpStepUpDialog.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
const backupStepUp = useStepUp()
|
||||
|
||||
// 敏感操作被 2FA 门控拦截时的统一提示。
|
||||
function reportStepUpBlocked(error: unknown): boolean {
|
||||
if (!isStepUpBlocked(error)) return false
|
||||
appStore.showError(
|
||||
stepUpBlockReason(error) === 'STEP_UP_ADMIN_API_KEY_FORBIDDEN'
|
||||
? t('stepUp.adminApiKeyForbidden')
|
||||
: t('stepUp.notEnabled')
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
// S3 config
|
||||
const s3Form = ref<BackupS3Config>({
|
||||
@@ -523,11 +538,15 @@ async function loadBackups() {
|
||||
async function createBackup() {
|
||||
creatingBackup.value = true
|
||||
try {
|
||||
const record = await adminAPI.backup.createBackup({ expire_days: manualExpireDays.value })
|
||||
const record = await backupStepUp.run(() => adminAPI.backup.createBackup({ expire_days: manualExpireDays.value }))
|
||||
// 插入到列表顶部
|
||||
backups.value.unshift(record)
|
||||
startPolling(record.id)
|
||||
} catch (error: any) {
|
||||
if (reportStepUpBlocked(error)) {
|
||||
creatingBackup.value = false
|
||||
return
|
||||
}
|
||||
if (error?.response?.status === 409) {
|
||||
appStore.showWarning(t('admin.backup.operations.alreadyInProgress'))
|
||||
} else {
|
||||
@@ -539,9 +558,10 @@ async function createBackup() {
|
||||
|
||||
async function downloadBackup(id: string) {
|
||||
try {
|
||||
const result = await adminAPI.backup.getDownloadURL(id)
|
||||
const result = await backupStepUp.run(() => adminAPI.backup.getDownloadURL(id))
|
||||
window.open(result.url, '_blank')
|
||||
} catch (error) {
|
||||
if (reportStepUpBlocked(error)) return
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1577,6 +1577,41 @@
|
||||
:disabled="!form.totp_encryption_key_configured"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 会话 IP/UA 绑定 -->
|
||||
<div
|
||||
class="flex items-center justify-between border-t border-gray-100 pt-4 dark:border-dark-700"
|
||||
>
|
||||
<div>
|
||||
<label class="font-medium text-gray-900 dark:text-white">{{
|
||||
t("admin.settings.security.sessionBinding")
|
||||
}}</label>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ t("admin.settings.security.sessionBindingHint") }}
|
||||
</p>
|
||||
</div>
|
||||
<Toggle v-model="form.session_binding_enabled" />
|
||||
</div>
|
||||
|
||||
<!-- 审计日志保留天数 -->
|
||||
<div
|
||||
class="flex items-center justify-between border-t border-gray-100 pt-4 dark:border-dark-700"
|
||||
>
|
||||
<div>
|
||||
<label class="font-medium text-gray-900 dark:text-white">{{
|
||||
t("admin.settings.security.auditRetention")
|
||||
}}</label>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ t("admin.settings.security.auditRetentionHint") }}
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
v-model.number="form.audit_log_retention_days"
|
||||
type="number"
|
||||
min="0"
|
||||
class="input w-28 text-right"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8157,6 +8192,8 @@ const form = reactive<SettingsForm>({
|
||||
password_reset_enabled: false,
|
||||
totp_enabled: false,
|
||||
totp_encryption_key_configured: false,
|
||||
session_binding_enabled: true,
|
||||
audit_log_retention_days: 180,
|
||||
login_agreement_enabled: false,
|
||||
login_agreement_mode: "modal",
|
||||
login_agreement_updated_at: "2026-03-31",
|
||||
@@ -9521,6 +9558,8 @@ async function saveSettings() {
|
||||
invitation_code_enabled: form.invitation_code_enabled,
|
||||
password_reset_enabled: form.password_reset_enabled,
|
||||
totp_enabled: form.totp_enabled,
|
||||
session_binding_enabled: form.session_binding_enabled,
|
||||
audit_log_retention_days: form.audit_log_retention_days,
|
||||
login_agreement_enabled: form.login_agreement_enabled,
|
||||
login_agreement_mode: form.login_agreement_mode,
|
||||
login_agreement_updated_at: form.login_agreement_updated_at,
|
||||
|
||||
Reference in new issue
Block a user