feat(密钥管理): 后台可代填并锁定用户代理设置,客户端只读并回填本地配置

代理是选配、不进 items 也不参与门禁,但客户端各任务链读的是本地 app.json 的
proxy_url,用户自填值与后台不一致时排查成本高。改法:

- 后台 PUT/DELETE /api/admin/user-secrets/{userId}/modules/{moduleKey} 代填/解锁,
  写入后该行 source=admin;数据权限走 resolveVisibleUserIds,超管不限;
- 客户端 save/clear 命中锁定行时服务端直接拒绝并给出原因(只置灰挡不住直接调接口);
- 密钥包把代理单独放 proxy 字段下发(仍不进 items、不影响 complete 判定),
  锁定时带 full 明文,客户端据此幂等地对齐本地配置;解锁 = 删除该行。

只开放代理代填:密钥模块要客户端提交任务时携带本地明文,代填会把用户卡死。
This commit is contained in:
2026-09-28 19:39:08 +08:00
parent 5dd11f7048
commit 8b4425dcbf
12 changed files with 583 additions and 20 deletions
@@ -33,6 +33,8 @@ export interface ApiSecretSnapshot {
/** 服务端脱敏值(权威展示,如 sk-a****1234)。 */
masked: string
exists: boolean
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空(当前仅代理模块)。 */
locked: boolean
checkStatus: ApiSecretCheckStatus
checkCode: string
checkMessage: string
@@ -41,6 +43,12 @@ export interface ApiSecretSnapshot {
updatedAt: number | null
}
/** 代理状态:由服务端单独下发(不在 items 内、不参与门禁);锁定时带完整地址。 */
export interface ServerProxySnapshot extends ApiSecretSnapshot {
/** 后台锁定的完整代理地址(未锁定时为空串)。 */
full: string
}
interface ApiSecretCacheEntry extends ApiSecretSnapshot {
schema: 2
}
@@ -69,6 +77,8 @@ let moduleInfos: ApiSecretModuleInfo[] = [...DEFAULT_MODULE_INFOS]
let requiredModules: string[] = [...DEFAULT_REQUIRED_MODULES]
let bundleLoaded = false
let inflightLoad: Promise<ApiSecretLoadState> | null = null
/** 服务端代理状态(后台锁定/检测展示用);未成功加载过为 null。 */
let serverProxy: ServerProxySnapshot | null = null
function currentUid(): string {
if (typeof window === 'undefined') return '0'
@@ -89,6 +99,7 @@ function emptyEntry(): ApiSecretCacheEntry {
value: '',
masked: '',
exists: false,
locked: false,
checkStatus: 'unknown',
checkCode: '',
checkMessage: '',
@@ -122,6 +133,7 @@ function readMirror(moduleKey: string): ApiSecretCacheEntry | null {
value: typeof parsed.value === 'string' ? parsed.value : '',
masked: typeof parsed.masked === 'string' ? parsed.masked : '',
exists: Boolean(parsed.exists),
locked: Boolean(parsed.locked),
checkStatus: normalizeCheckStatus(parsed.checkStatus),
checkCode: typeof parsed.checkCode === 'string' ? parsed.checkCode : '',
checkMessage: typeof parsed.checkMessage === 'string' ? parsed.checkMessage : '',
@@ -236,6 +248,7 @@ function applyServerItem(moduleKey: string, item: UserApiSecretItem) {
value: current.value,
masked: item.masked || '',
exists: Boolean(item.exists),
locked: Boolean(item.locked),
checkStatus: normalizeCheckStatus(item.checkStatus),
checkCode: item.checkCode || '',
checkMessage: item.checkMessage || '',
@@ -283,6 +296,11 @@ export function getStoredApiSecretSnapshot(moduleKey: ApiSecretModuleKey): ApiSe
return snapshot
}
/** 同步读服务端代理状态(含后台锁定标记与锁定时的完整地址)。 */
export function getServerProxySnapshot(): ServerProxySnapshot | null {
return serverProxy
}
export function subscribeApiSecrets(listener: () => void): () => void {
listeners.add(listener)
return () => {
@@ -330,6 +348,11 @@ async function doLoad(): Promise<ApiSecretLoadState> {
applyServerItem(item.moduleKey, item)
}
}
serverProxy = toServerProxy(bundle?.proxy)
if (serverProxy?.locked && serverProxy.full) {
// 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默
await syncLockedProxyToLocal(serverProxy.full)
}
bundleLoaded = true
notify()
const migrated = await tryMigrateLocalSecrets(bundle?.items || [])
@@ -420,6 +443,51 @@ function readLocalProxyUrl(config: Record<string, unknown> | null | undefined):
return typeof config?.proxy_url === 'string' ? config.proxy_url.trim() : ''
}
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
if (!proxy) return null
return {
value: '',
masked: proxy.masked || '',
exists: Boolean(proxy.exists),
locked: Boolean(proxy.locked),
full: typeof proxy.full === 'string' ? proxy.full.trim() : '',
checkStatus: normalizeCheckStatus(proxy.checkStatus),
checkCode: proxy.checkCode || '',
checkMessage: proxy.checkMessage || '',
checkLatencyMs: typeof proxy.checkLatencyMs === 'number' ? proxy.checkLatencyMs : null,
checkedAt: toMillis(proxy.checkedAt),
updatedAt: toMillis(proxy.updatedAt),
}
}
/**
* 后台代填并锁定的代理:把完整地址写入本地 app.json(proxy_users[uid],未登录回退全局),
* 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。
* 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。
*/
async function syncLockedProxyToLocal(full: string): Promise<void> {
try {
if (typeof window === 'undefined') return
const api = window.pywebview?.api
if (!api?.read_config || !api?.save_config) return
const config = (await api.read_config()) as Record<string, unknown> | null
if (readLocalProxyUrl(config) === full) return
const uid = currentUid()
if (uid === '0') {
const mode = Number(config?.proxy_mode) === 2 ? 2 : 1
await api.save_config({ proxy_url: full, proxy_mode: mode })
return
}
const users = (config?.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) as Record<string, unknown>
// save_config 对 proxy_users 只做 uid 级合并(保留其他用户),故同一对象内要带齐原有模式
const mode = Number(own.proxy_mode) === 2 ? 2 : 1
await api.save_config({ proxy_users: { [uid]: { proxy_url: full, proxy_mode: mode } } })
} catch (error) {
console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error)
}
}
/** 保存密钥到服务端;成功后刷新本地缓存(失败不写本地,避免本地有值服务端没有的假象)。 */
export async function saveApiSecret(moduleKey: ApiSecretModuleKey, value: string): Promise<ApiSecretSnapshot> {
const trimmed = value.trim()
@@ -472,6 +540,7 @@ export function clearApiSecretCache(): void {
memory.clear()
bundleLoaded = false
inflightLoad = null
serverProxy = null
}
/** 供测试与调试:模块级状态快照。 */