feat(monitor): admin channel monitor MVP with SSRF protection and batch aggregation

新增 admin「渠道监控」模块(参考 BingZi-233/check-cx),独立于现有 Channel 体系。
admin 配置 + 后台定时调用上游 LLM chat completions 健康检查 + 所有登录用户只读可见。

后端:
- ent: channel_monitor + channel_monitor_history(AES-256-GCM 加密 api_key)
- service 按职责拆分:service/aggregator/validate/checker/runner/ssrf
- provider strategy map 替代 switch(openai/anthropic/gemini)
- repository batch 聚合(ListLatestForMonitorIDs + ComputeAvailabilityForMonitors)消除 N+1
- runner: ticker(5s) + pond worker pool(5) + inFlight 防并发 + TrySubmit 防雪崩
  + 凌晨 3 点 cron 清理 30 天历史
- SSRF 防护:强制 https + 私网/loopback/云元数据 IP 拒绝(127/8、10/8、172.16/12、
  192.168/16、169.254/16、100.64/10、::1、fc00::/7、fe80::/10)+ DialContext
  在 socket 层防 DNS rebinding
- API key sanitize:擦除 url.Error 与上游响应 body 中的 sk-/sk-ant-/AIza/JWT 模式
- APIKeyDecryptFailed 标志位 + 单 monitor 路径检测,避免空 key 调用上游

handler:
- admin: CRUD + 手动触发 + 历史接口(api_key 脱敏)
- user: 只读列表 + 状态详情(去除 api_key/endpoint)
- ParseChannelMonitorID 共用 + dto.ChannelMonitorExtraModelStatus 共用

前端:
- 路由 /admin/channels/{pricing,monitor} + /monitor(用户只读)
- AppSidebar 父项 expandOnly 支持
- ChannelMonitorView 拆为 8 个子组件 + ChannelStatusView 拆出 detail dialog
- composables/useChannelMonitorFormat + constants/channelMonitor 共享
- i18n monitorCommon namespace 消除 admin/user 两 view 重复

合规:所有文件符合 CLAUDE.md(Go ≤ 500 行 / Vue ≤ 300 行 / 函数 ≤ 30 行)
CI: go build / gofmt / golangci-lint(0 issues) / make test-unit / pnpm build 全绿
This commit is contained in:
erio
2026-04-20 20:21:02 +08:00
parent 0b85a8da88
commit 20a4e41872
67 changed files with 14997 additions and 32 deletions

View File

@@ -0,0 +1,45 @@
<template>
<div class="flex items-center gap-1">
<button
@click="$emit('run', row)"
:disabled="running"
class="flex flex-col items-center gap-0.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-primary-600 dark:hover:bg-dark-700 dark:hover:text-primary-400"
>
<Icon name="refresh" size="sm" :class="running ? 'animate-spin' : ''" />
<span class="text-xs">{{ t('admin.channelMonitor.runNow') }}</span>
</button>
<button
@click="$emit('edit', row)"
class="flex flex-col items-center gap-0.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-primary-600 dark:hover:bg-dark-700 dark:hover:text-primary-400"
>
<Icon name="edit" size="sm" />
<span class="text-xs">{{ t('common.edit') }}</span>
</button>
<button
@click="$emit('delete', row)"
class="flex flex-col items-center gap-0.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:text-red-400"
>
<Icon name="trash" size="sm" />
<span class="text-xs">{{ t('common.delete') }}</span>
</button>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import type { ChannelMonitor } from '@/api/admin/channelMonitor'
import Icon from '@/components/icons/Icon.vue'
defineProps<{
row: ChannelMonitor
running: boolean
}>()
defineEmits<{
(e: 'run', row: ChannelMonitor): void
(e: 'edit', row: ChannelMonitor): void
(e: 'delete', row: ChannelMonitor): void
}>()
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,95 @@
<template>
<div class="flex flex-col justify-between gap-4 lg:flex-row lg:items-start">
<!-- Left: Search + Filters -->
<div class="flex flex-1 flex-wrap items-center gap-3">
<div class="relative w-full sm:w-64">
<Icon
name="search"
size="md"
class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500"
/>
<input
v-model="search"
type="text"
:placeholder="t('admin.channelMonitor.searchPlaceholder')"
class="input pl-10"
@input="$emit('search-input')"
/>
</div>
<Select
v-model="provider"
:options="providerFilterOptions"
:placeholder="t('admin.channelMonitor.allProviders')"
class="w-44"
@change="$emit('reload')"
/>
<Select
v-model="enabled"
:options="enabledFilterOptions"
:placeholder="t('admin.channelMonitor.enabledFilter')"
class="w-40"
@change="$emit('reload')"
/>
</div>
<!-- Right: Actions -->
<div class="flex w-full flex-shrink-0 flex-wrap items-center justify-end gap-3 lg:w-auto">
<button
@click="$emit('reload')"
:disabled="loading"
class="btn btn-secondary"
:title="t('common.refresh')"
>
<Icon name="refresh" size="md" :class="loading ? 'animate-spin' : ''" />
</button>
<button @click="$emit('create')" class="btn btn-primary">
<Icon name="plus" size="md" class="mr-2" />
{{ t('admin.channelMonitor.createButton') }}
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { Provider } from '@/api/admin/channelMonitor'
import Select from '@/components/common/Select.vue'
import Icon from '@/components/icons/Icon.vue'
import {
PROVIDER_OPENAI,
PROVIDER_ANTHROPIC,
PROVIDER_GEMINI,
} from '@/constants/channelMonitor'
defineProps<{
loading: boolean
}>()
defineEmits<{
(e: 'reload'): void
(e: 'create'): void
(e: 'search-input'): void
}>()
const search = defineModel<string>('search', { required: true })
const provider = defineModel<Provider | ''>('provider', { required: true })
const enabled = defineModel<'' | 'true' | 'false'>('enabled', { required: true })
const { t } = useI18n()
const providerFilterOptions = computed(() => [
{ value: '', label: t('admin.channelMonitor.allProviders') },
{ value: PROVIDER_OPENAI, label: t('monitorCommon.providers.openai') },
{ value: PROVIDER_ANTHROPIC, label: t('monitorCommon.providers.anthropic') },
{ value: PROVIDER_GEMINI, label: t('monitorCommon.providers.gemini') },
])
const enabledFilterOptions = computed(() => [
{ value: '', label: t('admin.channelMonitor.allStatus') },
{ value: 'true', label: t('admin.channelMonitor.onlyEnabled') },
{ value: 'false', label: t('admin.channelMonitor.onlyDisabled') },
])
</script>

View File

@@ -0,0 +1,297 @@
<template>
<BaseDialog
:show="show"
:title="editing ? t('admin.channelMonitor.editTitle') : t('admin.channelMonitor.createTitle')"
width="wide"
@close="$emit('close')"
>
<form id="channel-monitor-form" @submit.prevent="handleSubmit" class="space-y-5">
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.name') }} <span class="text-red-500">*</span></label>
<input v-model="form.name" type="text" required class="input" :placeholder="t('admin.channelMonitor.form.namePlaceholder')" />
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.provider') }} <span class="text-red-500">*</span></label>
<Select v-model="form.provider" :options="providerOptions" />
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.endpoint') }} <span class="text-red-500">*</span></label>
<div class="flex gap-2">
<input v-model="form.endpoint" type="text" required class="input flex-1" :placeholder="t('admin.channelMonitor.form.endpointPlaceholder')" />
<button type="button" @click="useCurrentDomain" class="btn btn-secondary whitespace-nowrap">
{{ t('admin.channelMonitor.form.useCurrentDomain') }}
</button>
</div>
</div>
<div>
<label class="input-label">
{{ t('admin.channelMonitor.form.apiKey') }}<span v-if="!editing" class="text-red-500"> *</span>
</label>
<div class="flex gap-2">
<input
v-model="form.api_key"
type="password"
:required="!editing"
class="input flex-1"
:placeholder="editing ? t('admin.channelMonitor.form.apiKeyEditPlaceholder') : t('admin.channelMonitor.form.apiKeyPlaceholder')"
/>
<button type="button" @click="openMyKeyPicker" class="btn btn-secondary whitespace-nowrap">
{{ t('admin.channelMonitor.form.useMyKey') }}
</button>
</div>
<p v-if="editing && editing.api_key_masked" class="mt-1 text-xs text-gray-400">{{ editing.api_key_masked }}</p>
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.primaryModel') }} <span class="text-red-500">*</span></label>
<input v-model="form.primary_model" type="text" required class="input" :placeholder="t('admin.channelMonitor.form.primaryModelPlaceholder')" />
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.extraModels') }}</label>
<ModelTagInput
:models="form.extra_models"
:placeholder="t('admin.channelMonitor.form.extraModelsPlaceholder')"
@update:models="form.extra_models = $event"
/>
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.groupName') }}</label>
<input v-model="form.group_name" type="text" class="input" :placeholder="t('admin.channelMonitor.form.groupNamePlaceholder')" />
</div>
<div>
<label class="input-label">{{ t('admin.channelMonitor.form.intervalSeconds') }} <span class="text-red-500">*</span></label>
<input v-model.number="form.interval_seconds" type="number" min="15" max="3600" required class="input" />
<p class="mt-1 text-xs text-gray-400">{{ t('admin.channelMonitor.form.intervalSecondsHint') }}</p>
</div>
<div class="flex items-center justify-between">
<label class="input-label mb-0">{{ t('admin.channelMonitor.form.enabled') }}</label>
<Toggle v-model="form.enabled" />
</div>
</form>
<template #footer>
<div class="flex justify-end gap-3">
<button @click="$emit('close')" type="button" class="btn btn-secondary">
{{ t('common.cancel') }}
</button>
<button
type="submit"
form="channel-monitor-form"
:disabled="submitting"
class="btn btn-primary"
>
{{ submitting
? t('common.submitting')
: editing ? t('common.update') : t('common.create') }}
</button>
</div>
</template>
</BaseDialog>
<MonitorKeyPickerDialog
:show="showKeyPicker"
:loading="myKeysLoading"
:keys="myActiveKeys"
@close="showKeyPicker = false"
@pick="pickMyKey"
/>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { extractApiErrorMessage } from '@/utils/apiError'
import { adminAPI } from '@/api/admin'
import { keysAPI } from '@/api/keys'
import type {
ChannelMonitor,
CreateParams,
Provider,
UpdateParams,
} from '@/api/admin/channelMonitor'
import type { ApiKey } from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
import Select from '@/components/common/Select.vue'
import Toggle from '@/components/common/Toggle.vue'
import ModelTagInput from '@/components/admin/channel/ModelTagInput.vue'
import MonitorKeyPickerDialog from '@/components/admin/monitor/MonitorKeyPickerDialog.vue'
import {
PROVIDER_OPENAI,
PROVIDER_ANTHROPIC,
PROVIDER_GEMINI,
DEFAULT_INTERVAL_SECONDS,
} from '@/constants/channelMonitor'
const props = defineProps<{
show: boolean
monitor: ChannelMonitor | null
}>()
const emit = defineEmits<{
(e: 'close'): void
(e: 'saved'): void
}>()
const { t } = useI18n()
const appStore = useAppStore()
// editing is true when we have an existing monitor
const editing = computed<ChannelMonitor | null>(() => props.monitor)
const submitting = ref(false)
// API key picker
const showKeyPicker = ref(false)
const myKeysLoading = ref(false)
const myActiveKeys = ref<ApiKey[]>([])
interface MonitorForm {
name: string
provider: Provider
endpoint: string
api_key: string
primary_model: string
extra_models: string[]
group_name: string
interval_seconds: number
enabled: boolean
}
const form = reactive<MonitorForm>({
name: '',
provider: PROVIDER_OPENAI,
endpoint: '',
api_key: '',
primary_model: '',
extra_models: [],
group_name: '',
interval_seconds: DEFAULT_INTERVAL_SECONDS,
enabled: true,
})
const providerOptions = computed(() => [
{ value: PROVIDER_OPENAI, label: t('monitorCommon.providers.openai') },
{ value: PROVIDER_ANTHROPIC, label: t('monitorCommon.providers.anthropic') },
{ value: PROVIDER_GEMINI, label: t('monitorCommon.providers.gemini') },
])
function resetForm() {
form.name = ''
form.provider = PROVIDER_OPENAI
form.endpoint = ''
form.api_key = ''
form.primary_model = ''
form.extra_models = []
form.group_name = ''
form.interval_seconds = DEFAULT_INTERVAL_SECONDS
form.enabled = true
}
function loadFromMonitor(m: ChannelMonitor) {
form.name = m.name
form.provider = m.provider
form.endpoint = m.endpoint
form.api_key = ''
form.primary_model = m.primary_model
form.extra_models = [...(m.extra_models || [])]
form.group_name = m.group_name || ''
form.interval_seconds = m.interval_seconds || DEFAULT_INTERVAL_SECONDS
form.enabled = m.enabled
}
// Re-sync form whenever the dialog is opened or the target monitor changes.
watch(
() => [props.show, props.monitor] as const,
([show, m]) => {
if (!show) return
if (m) loadFromMonitor(m)
else resetForm()
},
{ immediate: true },
)
function useCurrentDomain() {
form.endpoint = window.location.origin
}
async function openMyKeyPicker() {
showKeyPicker.value = true
if (myActiveKeys.value.length > 0) return
myKeysLoading.value = true
try {
const res = await keysAPI.list(1, 100, { status: 'active' })
const items = res.items || []
const now = Date.now()
myActiveKeys.value = items.filter(k => {
if (k.status !== 'active') return false
if (!k.expires_at) return true
return new Date(k.expires_at).getTime() > now
})
} catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('admin.channelMonitor.form.noActiveKey')))
} finally {
myKeysLoading.value = false
}
}
function pickMyKey(k: ApiKey) {
form.api_key = k.key
showKeyPicker.value = false
}
function buildPayload(): CreateParams {
return {
name: form.name.trim(),
provider: form.provider,
endpoint: form.endpoint.trim(),
api_key: form.api_key.trim(),
primary_model: form.primary_model.trim(),
extra_models: form.extra_models,
group_name: form.group_name.trim(),
enabled: form.enabled,
interval_seconds: form.interval_seconds,
}
}
async function handleSubmit() {
if (submitting.value) return
if (!form.name.trim()) {
appStore.showError(t('admin.channelMonitor.nameRequired'))
return
}
if (!form.primary_model.trim()) {
appStore.showError(t('admin.channelMonitor.primaryModelRequired'))
return
}
submitting.value = true
try {
const target = editing.value
if (target) {
const { api_key, ...rest } = buildPayload()
const req: UpdateParams = rest
// Only send api_key if user typed a new value
if (api_key) req.api_key = api_key
await adminAPI.channelMonitor.update(target.id, req)
appStore.showSuccess(t('admin.channelMonitor.updateSuccess'))
} else {
await adminAPI.channelMonitor.create(buildPayload())
appStore.showSuccess(t('admin.channelMonitor.createSuccess'))
}
emit('saved')
emit('close')
} catch (err: unknown) {
appStore.showError(extractApiErrorMessage(err, t('common.error')))
} finally {
submitting.value = false
}
}
</script>

View File

@@ -0,0 +1,64 @@
<template>
<BaseDialog
:show="show"
:title="t('admin.channelMonitor.form.selectKeyTitle')"
width="normal"
@close="$emit('close')"
>
<div class="space-y-3">
<p class="text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.channelMonitor.form.selectKeyHint') }}
</p>
<div v-if="loading" class="py-6 text-center text-sm text-gray-500">
{{ t('common.loading') }}
</div>
<div v-else-if="keys.length === 0" class="py-6 text-center text-sm text-gray-500">
{{ t('admin.channelMonitor.form.noActiveKey') }}
</div>
<div v-else class="max-h-72 space-y-1 overflow-auto">
<button
v-for="k in keys"
:key="k.id"
type="button"
@click="$emit('pick', k)"
class="block w-full rounded-lg border border-gray-200 px-3 py-2 text-left text-sm transition-colors hover:bg-gray-50 dark:border-dark-600 dark:hover:bg-dark-700"
>
<div class="font-medium text-gray-900 dark:text-white">{{ k.name }}</div>
<div class="font-mono text-xs text-gray-500 dark:text-gray-400">{{ maskKey(k.key) }}</div>
</button>
</div>
</div>
<template #footer>
<div class="flex justify-end">
<button @click="$emit('close')" class="btn btn-secondary">
{{ t('common.cancel') }}
</button>
</div>
</template>
</BaseDialog>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import type { ApiKey } from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
defineProps<{
show: boolean
loading: boolean
keys: ApiKey[]
}>()
defineEmits<{
(e: 'close'): void
(e: 'pick', key: ApiKey): void
}>()
const { t } = useI18n()
function maskKey(key: string): string {
if (!key) return ''
if (key.length <= 12) return `${key.slice(0, 4)}***`
return `${key.slice(0, 6)}...${key.slice(-4)}`
}
</script>

View File

@@ -0,0 +1,71 @@
<template>
<div class="flex items-center gap-2">
<span class="text-sm text-gray-900 dark:text-gray-100">{{ row.primary_model }}</span>
<HelpTooltip>
<template #trigger>
<span
class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium"
:class="statusBadgeClass(row.primary_status)"
>
{{ statusLabel(row.primary_status) }}
</span>
</template>
<div class="space-y-2">
<div class="text-xs font-semibold text-gray-100">
{{ row.primary_model }}
<span
class="ml-1 inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="statusBadgeClass(row.primary_status)"
>
{{ statusLabel(row.primary_status) }}
</span>
</div>
<div v-if="(row.extra_models?.length ?? 0) === 0" class="text-[11px] text-gray-300">
{{ t('monitorCommon.extraModelsEmpty') }}
</div>
<div v-else class="space-y-1">
<div class="text-[11px] font-semibold uppercase tracking-wide text-gray-400">
{{ t('monitorCommon.extraModelsHeader') }}
</div>
<table class="w-full text-left text-[11px]">
<thead>
<tr class="text-gray-400">
<th class="py-0.5 pr-2 font-medium">{{ t('admin.channelMonitor.columns.primaryModel') }}</th>
<th class="py-0.5 pr-2 font-medium">{{ t('admin.channelMonitor.columns.actions') }}</th>
<th class="py-0.5 font-medium">{{ t('admin.channelMonitor.columns.latency') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="m in (row.extra_models_status || [])" :key="m.model">
<td class="py-0.5 pr-2 text-gray-100">{{ m.model }}</td>
<td class="py-0.5 pr-2">
<span
class="inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px]"
:class="statusBadgeClass(m.status)"
>
{{ statusLabel(m.status) }}
</span>
</td>
<td class="py-0.5 text-gray-100">{{ formatLatency(m.latency_ms) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</HelpTooltip>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import type { ChannelMonitor } from '@/api/admin/channelMonitor'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import { useChannelMonitorFormat } from '@/composables/useChannelMonitorFormat'
defineProps<{
row: ChannelMonitor
}>()
const { t } = useI18n()
const { statusLabel, statusBadgeClass, formatLatency } = useChannelMonitorFormat()
</script>

View File

@@ -0,0 +1,56 @@
<template>
<BaseDialog
:show="show"
:title="t('admin.channelMonitor.runResultTitle')"
width="normal"
@close="$emit('close')"
>
<div class="space-y-2">
<div
v-for="r in results"
:key="r.model"
class="flex items-center justify-between rounded-lg border border-gray-200 px-3 py-2 text-sm dark:border-dark-600"
>
<div class="flex flex-col">
<span class="font-medium text-gray-900 dark:text-white">{{ r.model }}</span>
<span v-if="r.message" class="text-xs text-gray-500 dark:text-gray-400">{{ r.message }}</span>
</div>
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px]"
:class="statusBadgeClass(r.status)"
>
{{ statusLabel(r.status) }}
</span>
<span class="text-xs text-gray-500 dark:text-gray-400">{{ formatLatency(r.latency_ms) }} ms</span>
</div>
</div>
</div>
<template #footer>
<div class="flex justify-end">
<button @click="$emit('close')" class="btn btn-primary">
{{ t('common.close') }}
</button>
</div>
</template>
</BaseDialog>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import type { CheckResult } from '@/api/admin/channelMonitor'
import BaseDialog from '@/components/common/BaseDialog.vue'
import { useChannelMonitorFormat } from '@/composables/useChannelMonitorFormat'
defineProps<{
show: boolean
results: CheckResult[]
}>()
defineEmits<{
(e: 'close'): void
}>()
const { t } = useI18n()
const { statusLabel, statusBadgeClass, formatLatency } = useChannelMonitorFormat()
</script>