Files
crawler-plugin/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue
T
huangzd1997 bf7149e498 feat(密钥管理): 列表按用户聚合三字段列 + 代理配置服务端上报
- Java:后台列表一行一用户(货源查询密钥/外观专利密钥/代理设置),行级状态三项全通过才算通过;检测/清空改为按用户;搜索仅按用户名(去 UID);新增代理检测(经用户代理请求自家域名)与代理掩码(隐去账密)
- 后台前端:三字段列改版 + 行级状态筛选 + 用户名筛选
- 桌面前端:登录加载密钥时补报本地代理(只填空缺不覆盖)、保存/清空代理实时上报
2026-09-13 10:47:19 +08:00

639 lines
18 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="secret-settings-body">
<section v-for="module in modules" :key="module.moduleKey" class="secret-card">
<div class="secret-card-head">
<div>
<div class="secret-card-title">{{ module.moduleLabel }}</div>
<div class="secret-card-desc">{{ descriptionOf(module.moduleKey) }}</div>
</div>
<button
v-if="snapshotOf(module.moduleKey).exists"
type="button"
class="link-danger"
:disabled="busy"
@click="clearModule(module.moduleKey as ApiSecretModuleKey)"
>
清空
</button>
</div>
<input
v-model="moduleStates[module.moduleKey].input"
class="secret-input"
type="password"
:placeholder="placeholderOf(module.moduleKey)"
autocomplete="off"
spellcheck="false"
:disabled="busy"
/>
<div class="secret-actions">
<button
type="button"
class="check-btn"
:disabled="busy || moduleStates[module.moduleKey].checking"
@click="runCheck(module.moduleKey as ApiSecretModuleKey)"
>
{{ moduleStates[module.moduleKey].checking ? '检测中...' : (moduleStates[module.moduleKey].input.trim() ? '检测输入值' : '检测已存密钥') }}
</button>
<span class="check-result" :class="resultClassOf(module.moduleKey)">
{{ statusTextOf(module.moduleKey) }}
</span>
</div>
</section>
<section v-if="showProxy" class="secret-card">
<div class="secret-card-head">
<div>
<div class="secret-card-title">代理设置</div>
<div class="secret-card-desc">供客户端任务连接代理服务。</div>
</div>
</div>
<div class="proxy-field">
<label class="field-label" for="proxy-url">代理地址</label>
<input
id="proxy-url"
v-model="proxyUrl"
class="secret-input"
type="text"
placeholder="请输入代理地址"
autocomplete="off"
spellcheck="false"
:disabled="!proxyReady || busy"
@input="proxyDirty = true"
/>
</div>
<div class="retention-block">
<div class="field-label">代理模式</div>
<div class="retention-options">
<label
v-for="option in proxyModeOptions"
:key="option.value"
class="retention-option"
:class="{ 'retention-option--disabled': !proxyReady || busy }"
>
<input
v-model="proxyMode"
type="radio"
:value="option.value"
:disabled="!proxyReady || busy"
@change="proxyDirty = true"
/>
<span>{{ option.label }}</span>
</label>
</div>
</div>
<div class="secret-meta">
<span v-if="proxyLoading">正在读取代理配置...</span>
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
<span v-else-if="balanceLoading">正在查询代理余量...</span>
<span v-else-if="balance">{{ balanceText }}</span>
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
checkApiSecret,
clearApiSecret,
fetchProxyBalanceSafely,
getStoredApiSecretSnapshot,
listApiSecretModules,
loadApiSecrets,
saveApiSecret,
subscribeApiSecrets,
type ApiSecretCheckStatus,
type ApiSecretModuleKey,
type ApiSecretSnapshot,
type UserApiSecretCheckResult,
} from '@/shared/utils/api-secret-store'
import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview'
import { deleteMyApiSecret, putMyApiSecret } from '@/shared/api/types/modules/user-secret'
const props = withDefaults(
defineProps<{
/** 是否展示代理设置区(默认展示)。 */
showProxy?: boolean
}>(),
{
showProxy: true,
},
)
type ModuleState = {
input: string
checking: boolean
result: UserApiSecretCheckResult | null
error: string
}
const modules = ref(listApiSecretModules())
const moduleStates = reactive<Record<string, ModuleState>>({})
// 首次渲染即需可读:按模块清单预初始化状态(后续 refreshSnapshots 兜底补齐)
for (const module of modules.value) {
moduleStates[module.moduleKey] = { input: '', checking: false, result: null, error: '' }
}
const snapshots = ref<Record<string, ApiSecretSnapshot>>({})
const busy = ref(false)
const proxyUrl = ref('')
const proxyMode = ref<ProxyMode>(1)
const proxyLoading = ref(false)
const proxyLoadFailed = ref(false)
const proxyReady = ref(false)
const proxySupported = ref(false)
const proxyDirty = ref(false)
const balance = ref<{ surplus: string | null; balance: string | null } | null>(null)
const balanceLoading = ref(false)
const proxyModeOptions: Array<{ value: ProxyMode; label: string }> = [
{ value: 1, label: '白名单' },
{ value: 2, label: '账号密码' },
]
const MODULE_DESCRIPTIONS: Record<string, string> = {
'appearance-patent': '仅用于外观专利检测,保存在服务端并绑定当前账号。',
'similar-asin': '仅用于货源查询,保存在服务端并绑定当前账号。',
}
const balanceText = computed(() => {
if (!balance.value) return ''
const surplus = balance.value.surplus ?? '-'
const amount = balance.value.balance ?? '-'
return `套餐IP余量:${surplus} · 账户余额:${amount}`
})
function ensureModuleState(moduleKey: string) {
if (!moduleStates[moduleKey]) {
moduleStates[moduleKey] = { input: '', checking: false, result: null, error: '' }
}
return moduleStates[moduleKey]
}
function refreshSnapshots() {
modules.value = listApiSecretModules()
const next: Record<string, ApiSecretSnapshot> = {}
for (const module of modules.value) {
next[module.moduleKey] = getStoredApiSecretSnapshot(module.moduleKey as ApiSecretModuleKey)
ensureModuleState(module.moduleKey)
}
snapshots.value = next
}
function snapshotOf(moduleKey: string): ApiSecretSnapshot {
return snapshots.value[moduleKey] || getStoredApiSecretSnapshot(moduleKey as ApiSecretModuleKey)
}
function descriptionOf(moduleKey: string) {
return MODULE_DESCRIPTIONS[moduleKey] || '保存在服务端并绑定当前账号。'
}
function placeholderOf(moduleKey: string) {
const snapshot = snapshotOf(moduleKey)
if (snapshot.exists) {
return `已保存(${snapshot.masked || '****'}),输入新值可覆盖`
}
return '请输入 LLM 接口密钥'
}
const CHECK_STATUS_TEXT: Record<ApiSecretCheckStatus, string> = {
passed: '检测通过',
failed: '检测失败',
error: '暂时无法判定',
unknown: '已保存,未检测',
}
function formatTime(millis: number | null) {
if (!millis) return ''
const date = new Date(millis)
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${hour}:${minute}`
}
function statusTextOf(moduleKey: string) {
const state = ensureModuleState(moduleKey)
if (state.checking) return '正在检测...'
if (state.result) {
const latency = state.result.checkLatencyMs != null ? `(${state.result.checkLatencyMs}ms)` : ''
const suffix = state.result.viaProxy === true ? ' · 经代理' : ''
if (state.result.checkStatus === 'passed') return `检测通过${latency}${suffix}`
return `${state.result.checkMessage || '检测失败'}${suffix}`
}
if (state.error) return state.error
const snapshot = snapshotOf(moduleKey)
if (!snapshot.exists) return '当前未保存,请填写后保存'
const status = CHECK_STATUS_TEXT[snapshot.checkStatus] || '已保存'
const time = formatTime(snapshot.checkedAt)
const message = snapshot.checkStatus === 'unknown' ? '' : `:${snapshot.checkMessage || ''}`
return `${status}${message}${time ? ` · ${time}` : ''}`
}
function resultClassOf(moduleKey: string) {
const state = ensureModuleState(moduleKey)
const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus
return {
'check-result--ok': status === 'passed',
'check-result--fail': status === 'failed',
'check-result--warn': status === 'error',
}
}
async function runCheck(moduleKey: ApiSecretModuleKey) {
const state = ensureModuleState(moduleKey)
if (state.checking) return
state.checking = true
state.error = ''
state.result = null
const inputValue = state.input.trim()
try {
const result = await checkApiSecret(moduleKey, inputValue || undefined)
state.result = result
if (result.checkStatus === 'failed') {
ElMessage.warning(result.checkMessage || '密钥无效')
} else if (result.checkStatus === 'error') {
ElMessage.warning(result.checkMessage || '暂时无法判定密钥有效性')
} else {
ElMessage.success(inputValue ? '输入值检测通过(未保存)' : '密钥检测通过')
}
} catch (error) {
state.error = error instanceof Error ? error.message : '检测失败'
ElMessage.error(state.error)
} finally {
state.checking = false
refreshSnapshots()
}
}
async function clearModule(moduleKey: ApiSecretModuleKey) {
if (busy.value) return
busy.value = true
try {
await clearApiSecret(moduleKey)
const state = ensureModuleState(moduleKey)
state.input = ''
state.result = null
state.error = ''
refreshSnapshots()
ElMessage.success('已清空密钥')
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '清空失败')
} finally {
busy.value = false
}
}
function proxyUserId() {
if (typeof window === 'undefined') return '0'
return window.localStorage.getItem('uid') || '0'
}
/** 代理地址按登录用户隔离:proxy_users[uid],各自计费各自复用;
* 未登录(uid=0)回退全局 proxy_url(兼容旧版本已保存的配置)。 */
function readUserProxy(config: Record<string, unknown> | null | undefined) {
const uid = proxyUserId()
if (uid !== '0') {
const users = (config?.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) as Record<string, unknown>
return {
url: typeof own.proxy_url === 'string' ? own.proxy_url : '',
mode: Number(own.proxy_mode) === 2 ? 2 : 1,
}
}
return {
url: typeof config?.proxy_url === 'string' ? config.proxy_url : '',
mode: Number(config?.proxy_mode) === 2 ? 2 : 1,
}
}
function userProxyPatch(nextProxyUrl: string, nextProxyMode: ProxyMode) {
const uid = proxyUserId()
if (uid === '0') {
return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
}
const users: Record<string, unknown> = {}
users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
return { proxy_users: users }
}
async function loadProxyConfig() {
proxyLoading.value = true
proxyLoadFailed.value = false
proxyReady.value = false
proxyDirty.value = false
const api = getPywebviewApi()
proxySupported.value = Boolean(api?.read_config && api.save_config)
if (!api?.read_config || !api.save_config) {
proxyUrl.value = ''
proxyMode.value = 1
proxyLoading.value = false
return
}
try {
const config = await api.read_config()
const own = readUserProxy(config as Record<string, unknown>)
proxyUrl.value = own.url
proxyMode.value = (own.mode === 2 ? 2 : 1) as ProxyMode
proxyReady.value = true
} catch (error) {
proxyLoadFailed.value = true
ElMessage.error(error instanceof Error ? error.message : '代理配置读取失败')
} finally {
proxyLoading.value = false
}
}
/** 代理配置上报服务端(后台密钥管理观测/检测):有地址则保存、清空则删除;失败不阻断本地保存。 */
async function syncProxyToServer(url: string) {
if (proxyUserId() === '0') return
try {
if (url) {
await putMyApiSecret('proxy', url)
} else {
await deleteMyApiSecret('proxy')
}
} catch (error) {
console.warn('[api-secret] 代理配置上报失败(不影响本地任务):', error)
ElMessage.warning('代理已保存到本地,但上报后台失败')
}
}
async function loadBalance() {
balanceLoading.value = true
try {
const result = await fetchProxyBalanceSafely()
if (result?.available) {
balance.value = { surplus: result.surplus, balance: result.balance }
} else {
balance.value = null
}
} catch (error) {
console.warn('[api-secret] 代理余量查询失败:', error)
balance.value = null
} finally {
balanceLoading.value = false
}
}
/**
* 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存;
* 保存后对有输入值的模块自动检测一次,让用户立即知道密钥是否可用。
*/
async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean> {
if (busy.value || proxyLoading.value) return false
const pendingModules = modules.value.filter((module) => ensureModuleState(module.moduleKey).input.trim())
if (options.requireAll) {
const missing = modules.value.filter(
(module) => !ensureModuleState(module.moduleKey).input.trim() && !snapshotOf(module.moduleKey).exists,
)
if (missing.length) {
ElMessage.warning(`请填写:${missing.map((module) => module.moduleLabel).join('、')}`)
return false
}
}
busy.value = true
let secretsSaved = false
try {
for (const module of pendingModules) {
const moduleKey = module.moduleKey as ApiSecretModuleKey
await saveApiSecret(moduleKey, ensureModuleState(module.moduleKey).input.trim())
ensureModuleState(module.moduleKey).input = ''
}
secretsSaved = true
refreshSnapshots()
if (props.showProxy && proxyReady.value && proxyDirty.value) {
const api = getPywebviewApi()
if (!api?.save_config) throw new Error('当前客户端未提供代理配置保存能力')
const nextProxyUrl = proxyUrl.value.trim()
await api.save_config(userProxyPatch(nextProxyUrl, proxyMode.value) as DesktopConfigUpdate)
proxyUrl.value = nextProxyUrl
proxyDirty.value = false
await syncProxyToServer(nextProxyUrl)
}
// 保存成功的模块立即自动检测,结果直接反映在卡片状态行
for (const module of pendingModules) {
const moduleKey = module.moduleKey as ApiSecretModuleKey
try {
ensureModuleState(module.moduleKey).result = await checkApiSecret(moduleKey)
} catch (error) {
console.warn('[api-secret] 保存后自动检测失败:', error)
}
}
refreshSnapshots()
return true
} catch (error) {
const message = error instanceof Error ? error.message : '设置保存失败'
ElMessage.error(secretsSaved ? `密钥已保存,但后续步骤失败:${message}` : message)
return false
} finally {
busy.value = false
}
}
/** 重新从服务端拉取(设置页/弹窗打开时调用)。 */
async function reload() {
await loadApiSecrets({ force: true })
refreshSnapshots()
}
let unsubscribe: (() => void) | null = null
onMounted(() => {
refreshSnapshots()
unsubscribe = subscribeApiSecrets(refreshSnapshots)
void reload()
if (props.showProxy) {
void loadProxyConfig()
void loadBalance()
}
})
onUnmounted(() => {
if (unsubscribe) unsubscribe()
})
defineExpose({ saveAll, reload })
</script>
<style scoped>
.secret-settings-body {
display: flex;
flex-direction: column;
gap: 14px;
max-height: 62vh;
overflow-y: auto;
padding-right: 4px;
}
.secret-card {
padding: 18px;
border: 1px solid #313b46;
border-radius: 10px;
background: #20252b;
}
.secret-card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.secret-card-title {
color: #eef4fb;
font-size: 15px;
font-weight: 700;
}
.secret-card-desc {
margin-top: 4px;
color: #909ba8;
font-size: 12px;
line-height: 1.5;
}
.secret-input {
width: 100%;
height: 42px;
padding: 0 12px;
box-sizing: border-box;
border: 1px solid #3b4652;
border-radius: 10px;
background: #1b2026;
color: #dce6f0;
font-size: 13px;
outline: none;
}
.secret-input:focus {
border-color: #5b96d6;
}
.secret-input:disabled {
color: #707b86;
cursor: not-allowed;
opacity: .72;
}
.secret-actions {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
}
.check-btn {
height: 32px;
padding: 0 14px;
border: 1px solid #3c4a58;
border-radius: 8px;
background: #262e37;
color: #dbe5f0;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.check-btn:hover:not(:disabled) {
border-color: #4c647d;
}
.check-btn:disabled {
cursor: not-allowed;
opacity: .6;
}
.check-result {
color: #7f8a96;
font-size: 12px;
line-height: 1.5;
}
.check-result--ok {
color: #7fd6a4;
}
.check-result--fail {
color: #ff9b9b;
}
.check-result--warn {
color: #f0c674;
}
.proxy-field .field-label {
display: block;
}
.retention-block {
margin-top: 12px;
}
.field-label {
margin-bottom: 8px;
color: #a3afbb;
font-size: 12px;
}
.retention-options {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.retention-option {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border-radius: 999px;
background: #1b2026;
color: #dce4ec;
font-size: 12px;
cursor: pointer;
}
.retention-option input {
margin: 0;
}
.retention-option--disabled {
cursor: not-allowed;
opacity: .6;
}
.secret-meta {
margin-top: 10px;
color: #7f8a96;
font-size: 12px;
}
.link-danger {
border: none;
background: transparent;
color: #ff9b9b;
font-size: 12px;
cursor: pointer;
padding: 0;
}
.link-danger:disabled {
cursor: not-allowed;
opacity: .55;
}
</style>