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
@@ -9,6 +9,8 @@ export interface AdminUserSecretModule {
/** 完整明文值:仅代理列有值(后端对密钥列不下发明文)。 */
full: string
exists: boolean
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空。 */
locked: boolean
checkStatus: string
checkCode: string
checkMessage: string
@@ -90,3 +92,19 @@ export async function deleteUserSecret(userId: number): Promise<void> {
const { data } = await http.delete(`/api/admin/user-secrets/${userId}`)
unwrap<unknown>(data)
}
/** 代填并锁定该用户某模块配置(当前仅代理):PUT /api/admin/user-secrets/{userId}/modules/{moduleKey} */
export async function saveUserSecretModule(
userId: number,
moduleKey: string,
value: string,
): Promise<AdminUserSecretModule> {
const { data } = await http.put(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`, { value })
return unwrap<AdminUserSecretModule>(data)
}
/** 清空该用户某模块配置并解除锁定:DELETE /api/admin/user-secrets/{userId}/modules/{moduleKey} */
export async function clearUserSecretModule(userId: number, moduleKey: string): Promise<void> {
const { data } = await http.delete(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`)
unwrap<unknown>(data)
}
@@ -5,8 +5,10 @@ import { formatDateTime } from '@/utils/datetime'
import OldPagination from '@/components/OldPagination.vue'
import {
checkUserSecret,
clearUserSecretModule,
deleteUserSecret,
fetchUserSecretList,
saveUserSecretModule,
type AdminUserSecretModule,
type AdminUserSecretRow,
type GroupOption,
@@ -29,6 +31,8 @@ const groupFilter = ref<number | null>(null)
const groupOptions = ref<GroupOption[]>([])
/** 正在检测的行 userId,用于按钮 loading 态。 */
const checkingId = ref<number | null>(null)
/** 正在代填/解锁代理的行 userId,避免重复点击。 */
const proxyBusyId = ref<number | null>(null)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
@@ -77,11 +81,12 @@ function moduleStatusMeta(module: AdminUserSecretModule | undefined) {
}
}
/** 单格悬停详情:完整值(代理为全量地址)+ 检测消息 + 检测时间 + 耗时。 */
/** 单格悬停详情:完整值(代理为全量地址)+ 锁定说明 + 检测消息 + 检测时间 + 耗时。 */
function moduleTooltip(module: AdminUserSecretModule | undefined) {
if (!module || !module.exists) return '未配置'
const parts: string[] = []
if (module.full) parts.push(module.full)
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空')
if (module.checkMessage) parts.push(module.checkMessage)
if (module.checkedAt) parts.push(`检测时间:${formatDateTime(module.checkedAt)}`)
if (module.checkLatencyMs != null) parts.push(`耗时:${module.checkLatencyMs}ms`)
@@ -163,7 +168,7 @@ async function check(row: AdminUserSecretRow) {
async function remove(row: AdminUserSecretRow) {
const who = row.username || `UID ${row.userId}`
if (!window.confirm(`确定清空「${who}」的全部密钥与代理配置吗?清空后该用户需要重新配置。`)) return
if (!window.confirm(`确定清空「${who}」的全部密钥与代理配置吗?后台锁定的代理会一并清除并解锁,该用户需要重新配置。`)) return
try {
await deleteUserSecret(row.userId)
ElMessage.success('已清空')
@@ -173,6 +178,47 @@ async function remove(row: AdminUserSecretRow) {
}
}
/** 代填并锁定代理:写入后客户端只能查看,修改/清空会被服务端拒绝。 */
async function fillProxy(row: AdminUserSecretRow) {
const who = row.username || `UID ${row.userId}`
const value = window.prompt(
`代填「${who}」的代理地址(保存后客户端不可修改或清空,如需变更先解锁):`,
row.proxy?.full || '',
)
if (value == null) return
const trimmed = value.trim()
if (!trimmed) {
ElMessage.warning('代理地址不能为空')
return
}
proxyBusyId.value = row.userId
try {
await saveUserSecretModule(row.userId, 'proxy', trimmed)
ElMessage.success(row.proxy?.locked ? '已更新锁定代理' : '已代填并锁定代理')
load()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '代填失败')
} finally {
proxyBusyId.value = null
}
}
/** 解锁代理:清空后台代填值,该用户恢复自行配置。 */
async function unlockProxy(row: AdminUserSecretRow) {
const who = row.username || `UID ${row.userId}`
if (!window.confirm(`确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`)) return
proxyBusyId.value = row.userId
try {
await clearUserSecretModule(row.userId, 'proxy')
ElMessage.success('已解锁')
load()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '解锁失败')
} finally {
proxyBusyId.value = null
}
}
function changePage(next: number) {
if (next < 1 || next > totalPages.value) return
page.value = next
@@ -235,7 +281,7 @@ onMounted(load)
<th style="width: 130px">状态</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
<th style="width: 170px">操作</th>
<th style="width: 250px">操作</th>
</tr>
</thead>
<tbody>
@@ -270,8 +316,17 @@ onMounted(load)
<div class="module-cell module-cell--stack">
<span v-if="row.proxy?.exists" class="mono-mask mono-full" :title="moduleTooltip(row.proxy)">{{ row.proxy.full || row.proxy.masked }}</span>
<span v-else class="empty-value">未配置</span>
<span class="wh-pill" :class="moduleStatusMeta(row.proxy).tone" :title="moduleTooltip(row.proxy)">
{{ moduleStatusMeta(row.proxy).label }}
<span class="module-cell-pills">
<span class="wh-pill" :class="moduleStatusMeta(row.proxy).tone" :title="moduleTooltip(row.proxy)">
{{ moduleStatusMeta(row.proxy).label }}
</span>
<span
v-if="row.proxy?.locked"
class="wh-pill is-locked"
title="已由管理员代填并锁定:客户端不可修改或清空"
>
已锁定
</span>
</span>
</div>
</td>
@@ -291,6 +346,23 @@ onMounted(load)
>
{{ checkingId === row.userId ? '检测中…' : '立即检测' }}
</button>
<button
class="btn btn-sm btn-ghost"
type="button"
:disabled="proxyBusyId === row.userId"
@click="fillProxy(row)"
>
{{ row.proxy?.locked ? '改代理' : '代填代理' }}
</button>
<button
v-if="row.proxy?.locked"
class="btn btn-sm btn-ghost"
type="button"
:disabled="proxyBusyId === row.userId"
@click="unlockProxy(row)"
>
解锁
</button>
<button class="btn btn-sm btn-danger" type="button" @click="remove(row)">清空</button>
</td>
</tr>
@@ -525,6 +597,7 @@ h3 {
.ops-cell {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.empty-tip {
color: #8293a5;
@@ -561,4 +634,15 @@ h3 {
border-color: #d6dee6;
color: #6b7d8f;
}
.wh-pill.is-locked {
background: #f0ecfb;
border-color: #d5caf0;
color: #5b4a96;
}
.module-cell-pills {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
</style>
@@ -5,6 +5,8 @@ import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretPageVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
@@ -12,11 +14,14 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -26,12 +31,13 @@ import java.util.Map;
/**
* 后台密钥管理:一行一用户(货源查询密钥 / 外观专利密钥 / 代理设置 三字段列),
* 管理员查看脱敏值、立即检测、清空。不提供查看明文与代填编辑能力。
* 管理员查看脱敏值、立即检测、清空,并可为用户代填并锁定代理设置
* (锁定后客户端只能查看,清空/修改会被服务端拒绝;密钥列不下发明文,故不开放代填)。
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin/user-secrets")
@Tag(name = "后台密钥管理", description = "按用户查看密钥与代理配置(脱敏)、立即检测连通性、清空。")
@Tag(name = "后台密钥管理", description = "按用户查看密钥与代理配置(脱敏)、立即检测连通性、代填并锁定代理、清空。")
public class AdminUserApiSecretController {
private final UserApiSecretService userApiSecretService;
@@ -76,6 +82,30 @@ public class AdminUserApiSecretController {
return ApiResponse.success("已清空", deleted);
}
@PutMapping("/{userId}/modules/{moduleKey}")
@Operation(summary = "代填并锁定该用户某模块配置",
description = "当前仅支持代理设置:写入后客户端只能查看,清空/修改会被拒绝。主管仅能操作自己数据权限范围内的用户。")
public ApiResponse<AdminUserSecretModuleVo> saveModule(
HttpServletRequest request,
@Parameter(description = "用户ID", required = true) @PathVariable Long userId,
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
return ApiResponse.success("已代填并锁定",
userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue()));
}
@DeleteMapping("/{userId}/modules/{moduleKey}")
@Operation(summary = "清空该用户某模块配置并解除锁定", description = "解锁后该用户可在客户端自行配置。")
public ApiResponse<Void> clearModule(
HttpServletRequest request,
@Parameter(description = "用户ID", required = true) @PathVariable Long userId,
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
userApiSecretService.adminClearModule(operator, userId, moduleKey);
return ApiResponse.success("已清空并解除锁定", null);
}
@PostMapping("/check-all")
@Operation(summary = "手动触发一轮全量巡检", description = "同步执行,受巡检条数与时间预算配置约束,请勿频繁调用。")
public ApiResponse<Map<String, Integer>> checkAll(HttpServletRequest request) {
@@ -24,6 +24,9 @@ public class AdminUserSecretModuleVo {
@Schema(description = "是否已配置")
private Boolean exists;
@Schema(description = "是否由后台代填并锁定:锁定时客户端不可修改或清空")
private Boolean locked;
@Schema(description = "连通性状态:unknown/passed/failed/error")
private String checkStatus;
@@ -15,6 +15,9 @@ public class UserApiSecretBundleVo {
@Schema(description = "必须配置的模块 key 列表(服务端下发,客户端不硬编码)")
private List<String> requiredModules;
@Schema(description = "代理设置状态:不在 items 内(不参与门禁);后台代填并锁定时 full 下发完整地址")
private UserApiSecretItemVo proxy;
@Schema(description = "是否配置完整:全部 required 模块均检测通过(error 状态视为放行)")
private Boolean complete;
}
@@ -18,9 +18,15 @@ public class UserApiSecretItemVo {
@Schema(description = "脱敏值,如 sk-a****1234")
private String masked;
@Schema(description = "完整明文值:仅代理模块被后台代填并锁定时下发(客户端写入本地配置用),其余情况为空")
private String full;
@Schema(description = "是否已配置")
private Boolean exists;
@Schema(description = "是否由后台代填并锁定:锁定时客户端不可修改或清空")
private Boolean locked;
@Schema(description = "连通性状态:unknown/passed/failed/error")
private String checkStatus;
@@ -101,7 +101,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
/** 当前用户密钥包:仅必填模块(代理为选配,不下发)+ 服务端下发的必填清单 + 完整性判定。 */
/** 当前用户密钥包:items 仅必填模块(代理为选配,单独走 proxy 字段不参与门禁)+ 必填清单 + 完整性判定。 */
public UserApiSecretBundleVo bundle(Long userId) {
requireUserId(userId);
List<UserSecretModule> required = UserSecretModule.requiredModules();
@@ -113,6 +113,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
vo.setItems(items);
vo.setRequiredModules(required.stream().map(UserSecretModule::key).toList());
vo.setComplete(isComplete(items));
vo.setProxy(toItem(UserSecretModule.PROXY, selectOne(userId, UserSecretModule.PROXY.key())));
return vo;
}
@@ -120,11 +121,13 @@ public class UserApiSecretService implements UserSecretCleanupPort {
* 保存密钥:加密落库并重置检测状态为 unknown;
* 若该值与用户刚检测过的输入值完全一致,则沿用那次检测结果(见 {@link #applyPendingVerification}),
* 其余情况仍由用户在保存后手动点「检测」确认。
* 后台代填并锁定的模块(source=admin)客户端不可覆盖。
*/
@Transactional
public UserApiSecretItemVo save(Long userId, String moduleKey, String value) {
requireUserId(userId);
UserSecretModule module = requireModule(moduleKey);
requireNotAdminLocked(userId, module, "修改");
String plainValue = normalize(value);
if (plainValue.isEmpty()) {
throw new BusinessException(module == UserSecretModule.PROXY ? "代理地址不能为空" : "密钥不能为空");
@@ -138,17 +141,78 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return toItem(module, selectOne(userId, module.key()));
}
/** 清空密钥。 */
/** 清空密钥。后台代填并锁定的模块不可清空。 */
@Transactional
public void clear(Long userId, String moduleKey) {
requireUserId(userId);
UserSecretModule module = requireModule(moduleKey);
requireNotAdminLocked(userId, module, "清空");
userApiSecretMapper.delete(new LambdaQueryWrapper<UserApiSecretEntity>()
.eq(UserApiSecretEntity::getUserId, userId)
.eq(UserApiSecretEntity::getModuleKey, module.key()));
log.info("[user-secret] 密钥已清空 userId={} module={}", userId, module.key());
}
/**
* 后台代填并锁定:写入后该模块 source=admin,客户端不可修改或清空。
* 目前仅开放代理设置——密钥模块要由客户端提交任务时携带本地明文,代填会让用户用不了。
* 数据权限:超管可操作全部用户,其余管理员限自己数据权限范围内的用户。
*/
@Transactional
public AdminUserSecretModuleVo adminSaveModule(AdminUserEntity operator, Long userId, String moduleKey, String value) {
requireUserId(userId);
requireVisibleUser(operator, userId);
UserSecretModule module = requireModule(moduleKey);
if (module != UserSecretModule.PROXY) {
throw new BusinessException("当前仅支持后台代填并锁定代理设置");
}
String plainValue = normalize(value);
if (plainValue.isEmpty()) {
throw new BusinessException("代理地址不能为空");
}
validateProxyValue(plainValue);
upsert(userId, module.key(), plainValue, SOURCE_ADMIN);
log.info("[user-secret] 后台代填并锁定配置 userId={} module={} operatorId={}",
userId, module.key(), operator == null ? null : operator.getId());
return toModuleVo(module, selectOne(userId, module.key()));
}
/** 后台清空某模块配置并解除锁定;解锁后客户端恢复自行配置。 */
@Transactional
public void adminClearModule(AdminUserEntity operator, Long userId, String moduleKey) {
requireUserId(userId);
requireVisibleUser(operator, userId);
UserSecretModule module = requireModule(moduleKey);
int deleted = userApiSecretMapper.delete(new LambdaQueryWrapper<UserApiSecretEntity>()
.eq(UserApiSecretEntity::getUserId, userId)
.eq(UserApiSecretEntity::getModuleKey, module.key()));
log.info("[user-secret] 后台清空并解除锁定 userId={} module={} 删除={} 条 operatorId={}",
userId, module.key(), deleted, operator == null ? null : operator.getId());
}
/** 是否后台代填并锁定:锁定行客户端不可改也不可清。 */
private boolean isAdminLocked(UserApiSecretEntity row) {
return row != null && row.getSource() != null && SOURCE_ADMIN.equalsIgnoreCase(row.getSource().trim());
}
/** 客户端写操作前置校验:锁定行直接拒绝并说明原因。 */
private void requireNotAdminLocked(Long userId, UserSecretModule module, String action) {
if (isAdminLocked(selectOne(userId, module.key()))) {
throw new BusinessException("该配置已由管理员设置并锁定,无法" + action + ";如需变更请联系管理员");
}
}
/** 数据权限:超管可操作全部;其余管理员只能操作自己数据权限范围内的用户。 */
private void requireVisibleUser(AdminUserEntity operator, Long userId) {
if (operator != null && "super_admin".equals(adminAuthSupport.currentRole(operator))) {
return;
}
Long operatorId = operator == null ? null : operator.getId();
if (!userDataScopeSupport.resolveVisibleUserIds(operatorId).contains(userId)) {
throw new BusinessException("无权操作该用户");
}
}
/** 本地密钥首次迁移:只写服务端空缺的模块,绝不覆盖已有值;忽略已废弃模块 key(如专利汇)。 */
@Transactional
public int migrateIfAbsent(Long userId, List<UserApiSecretMigrateRequest.Item> items) {
@@ -864,6 +928,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
if (row == null) {
vo.setMasked("");
vo.setExists(false);
vo.setLocked(false);
vo.setCheckStatus(STATUS_UNKNOWN);
vo.setCheckCode("");
vo.setCheckMessage("");
@@ -876,6 +941,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
vo.setFull(plain);
}
vo.setExists(hasText(plain));
vo.setLocked(isAdminLocked(row));
vo.setCheckStatus(hasText(row.getCheckStatus()) ? row.getCheckStatus() : STATUS_UNKNOWN);
vo.setCheckCode(row.getCheckCode());
vo.setCheckMessage(row.getCheckMessage());
@@ -892,6 +958,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
if (row == null) {
vo.setMasked("");
vo.setExists(false);
vo.setLocked(false);
vo.setCheckStatus(STATUS_UNKNOWN);
vo.setCheckCode("");
vo.setCheckMessage("");
@@ -899,7 +966,12 @@ public class UserApiSecretService implements UserSecretCleanupPort {
}
String plain = decryptQuietly(row.getSecretValue());
vo.setMasked(maskValue(module, plain));
// 锁定代理要下发完整地址:客户端据此把本地配置对齐到后台值(其余模块不下发明文)
if (module == UserSecretModule.PROXY && isAdminLocked(row)) {
vo.setFull(plain);
}
vo.setExists(hasText(plain));
vo.setLocked(isAdminLocked(row));
vo.setCheckStatus(hasText(row.getCheckStatus()) ? row.getCheckStatus() : STATUS_UNKNOWN);
vo.setCheckCode(row.getCheckCode());
vo.setCheckMessage(row.getCheckMessage());
@@ -1,6 +1,10 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
@@ -340,6 +344,9 @@ class UserApiSecretServiceTest {
assertThat(bundle.getItems()).extracting(item -> item.getModuleKey())
.containsExactlyInAnyOrder("appearance-patent", "similar-asin");
assertThat(bundle.getRequiredModules()).doesNotContain("proxy");
// 未锁定的代理既不下发明文,也不参与门禁
assertThat(bundle.getProxy().getLocked()).isFalse();
assertThat(bundle.getProxy().getFull()).isNull();
}
@Test
@@ -569,6 +576,160 @@ class UserApiSecretServiceTest {
verify(mapper).delete(any());
}
/** 后台代填并锁定的代理:客户端再提交就被拒(不落库),文案说明原因与出路。 */
@Test
void clientSaveRejectedWhenAdminLocked() {
UserApiSecretService service = newService();
UserApiSecretEntity locked = new UserApiSecretEntity();
locked.setId(5L);
locked.setUserId(7L);
locked.setModuleKey("proxy");
locked.setSecretValue("enc:https://api.jikip.com/ip-get?num=1&key=abc");
locked.setSource(UserApiSecretService.SOURCE_ADMIN);
when(mapper.selectOne(any())).thenReturn(locked);
org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.save(7L, "proxy", "http://1.2.3.4:8080"))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class)
.hasMessageContaining("已由管理员设置并锁定")
.hasMessageContaining("修改");
verify(mapper, never()).updateById(any(UserApiSecretEntity.class));
verify(mapper, never()).insert(any(UserApiSecretEntity.class));
}
/** 锁定行同样不可清空:清空按钮绕不过服务端。 */
@Test
void clientClearRejectedWhenAdminLocked() {
UserApiSecretService service = newService();
UserApiSecretEntity locked = new UserApiSecretEntity();
locked.setId(5L);
locked.setSecretValue("enc:https://api.jikip.com/ip-get?num=1&key=abc");
locked.setSource("ADMIN");
when(mapper.selectOne(any())).thenReturn(locked);
org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.clear(7L, "proxy"))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class)
.hasMessageContaining("已由管理员设置并锁定")
.hasMessageContaining("清空");
verify(mapper, never()).delete(any());
}
/** 非锁定行不受影响:客户端照常覆盖自己的配置。 */
@Test
void clientSaveStillWorksWhenSourceIsClient() {
UserApiSecretService service = newService();
UserApiSecretEntity existing = new UserApiSecretEntity();
existing.setId(5L);
existing.setSecretValue("enc:old");
existing.setSource(UserApiSecretService.SOURCE_CLIENT);
when(mapper.selectOne(any())).thenReturn(existing);
service.save(7L, "proxy", "http://1.2.3.4:8080");
assertThat(existing.getSource()).isEqualTo(UserApiSecretService.SOURCE_CLIENT);
assertThat(existing.getSecretValue()).isEqualTo("enc:http://1.2.3.4:8080");
}
/** 后台代填:写入 source=admin(锁定)并把完整地址回给后台列表。 */
@Test
void adminSaveModuleLocksProxyAndReturnsLockedVo() {
UserApiSecretService service = newService();
UserApiSecretEntity stored = new UserApiSecretEntity();
when(mapper.selectOne(any())).thenAnswer(inv -> stored.getId() == null ? null : stored);
when(mapper.insert(any(UserApiSecretEntity.class))).thenAnswer(inv -> {
UserApiSecretEntity arg = inv.getArgument(0);
stored.setId(1L);
stored.setUserId(arg.getUserId());
stored.setModuleKey(arg.getModuleKey());
stored.setSecretValue(arg.getSecretValue());
stored.setSource(arg.getSource());
stored.setCheckStatus(arg.getCheckStatus());
return 1;
});
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
AdminUserSecretModuleVo vo = service.adminSaveModule(operator, 7L, "proxy",
"https://api.jikip.com/ip-get?num=1&key=abc");
assertThat(stored.getSource()).isEqualTo(UserApiSecretService.SOURCE_ADMIN);
assertThat(vo.getExists()).isTrue();
assertThat(vo.getLocked()).isTrue();
assertThat(vo.getFull()).isEqualTo("https://api.jikip.com/ip-get?num=1&key=abc");
assertThat(vo.getMasked()).isEqualTo("https://api.jikip.com");
}
/** 密钥模块不开放后台代填:客户端提交任务要本地明文,代填会把用户卡死。 */
@Test
void adminSaveModuleRejectsKeyModules() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
org.assertj.core.api.Assertions.assertThatThrownBy(
() -> service.adminSaveModule(operator, 7L, "similar-asin", "sk-x"))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class)
.hasMessageContaining("仅支持后台代填并锁定代理设置");
verify(mapper, never()).insert(any(UserApiSecretEntity.class));
}
/** 代填代理同样要过数据权限:主管只能代填自己范围内的用户。 */
@Test
void adminSaveModuleEnforcesDataScope() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of(1L, 88L));
org.assertj.core.api.Assertions.assertThatThrownBy(
() -> service.adminSaveModule(operator, 7L, "proxy", "http://1.2.3.4:8080"))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class)
.hasMessageContaining("无权操作该用户");
verify(mapper, never()).insert(any(UserApiSecretEntity.class));
}
/** 后台清空某模块 = 解除锁定:删掉该行,客户端恢复自行配置。 */
@Test
void adminClearModuleDeletesOnlyThatModule() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
service.adminClearModule(operator, 7L, "proxy");
verify(mapper).delete(any());
}
/** 密钥包带代理状态(不占 items、不影响门禁);锁定时下发完整地址供客户端对齐本地配置。 */
@Test
void bundleShipsLockedProxyOutsideItems() {
UserApiSecretService service = newService();
UserApiSecretEntity proxyRow = new UserApiSecretEntity();
proxyRow.setUserId(7L);
proxyRow.setModuleKey("proxy");
proxyRow.setSecretValue("enc:https://api.jikip.com/ip-get?num=1&key=abc");
proxyRow.setSource(UserApiSecretService.SOURCE_ADMIN);
// 条件值要构建 SQL 段才写入参数表,而 mock 不会建 SQL;先注册实体元数据,stub 内手动触发一次
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
UserApiSecretEntity.class);
when(mapper.selectOne(any())).thenAnswer(inv -> {
LambdaQueryWrapper<UserApiSecretEntity> wrapper = inv.getArgument(0);
wrapper.getSqlSegment();
return wrapper.getParamNameValuePairs().containsValue("proxy") ? proxyRow : null;
});
UserApiSecretBundleVo bundle = service.bundle(7L);
assertThat(bundle.getItems()).hasSize(2);
assertThat(bundle.getComplete()).isFalse();
assertThat(bundle.getProxy().getExists()).isTrue();
assertThat(bundle.getProxy().getLocked()).isTrue();
assertThat(bundle.getProxy().getFull()).isEqualTo("https://api.jikip.com/ip-get?num=1&key=abc");
assertThat(bundle.getProxy().getMasked()).isEqualTo("https://api.jikip.com");
}
private AdminUserSecretModuleVo moduleVo(boolean exists, String status) {
AdminUserSecretModuleVo vo = new AdminUserSecretModuleVo();
vo.setExists(exists);
@@ -12,7 +12,11 @@ export interface UserApiSecretItem {
moduleKey: string
moduleLabel: string
masked: string
/** 完整明文值:仅代理模块被后台代填并锁定时下发,供客户端写入本地配置;其余情况为空。 */
full?: string | null
exists: boolean
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空。 */
locked?: boolean
checkStatus: string
checkCode: string
checkMessage: string
@@ -24,6 +28,8 @@ export interface UserApiSecretItem {
export interface UserApiSecretBundle {
items: UserApiSecretItem[]
requiredModules: string[]
/** 代理设置状态:不在 items 内(不参与门禁);后台锁定时 full 下发完整地址。 */
proxy?: UserApiSecretItem | null
complete: boolean
}
@@ -45,8 +45,15 @@
<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 class="secret-card-title">
代理设置
<span v-if="proxyLocked" class="lock-tag">后台锁定</span>
</div>
<div class="secret-card-desc">
{{ proxyLocked
? '代理由管理员统一配置并锁定,客户端不可修改或清空;如需变更请联系管理员。'
: '供客户端任务连接代理服务,支持静态代理地址或代理服务商的提取链接。' }}
</div>
</div>
</div>
@@ -60,7 +67,7 @@
placeholder="如 http://user:pass@host:port 或代理提取链接"
autocomplete="off"
spellcheck="false"
:disabled="!proxyReady || busy"
:disabled="!proxyReady || busy || proxyLocked"
@input="proxyDirty = true"
/>
</div>
@@ -72,13 +79,13 @@
v-for="option in proxyModeOptions"
:key="option.value"
class="retention-option"
:class="{ 'retention-option--disabled': !proxyReady || busy }"
:class="{ 'retention-option--disabled': !proxyReady || busy || proxyLocked }"
>
<input
v-model="proxyMode"
type="radio"
:value="option.value"
:disabled="!proxyReady || busy"
:disabled="!proxyReady || busy || proxyLocked"
@change="proxyDirty = true"
/>
<span>{{ option.label }}</span>
@@ -119,6 +126,7 @@ import {
checkApiSecret,
clearApiSecret,
fetchProxyBalanceSafely,
getServerProxySnapshot,
getStoredApiSecretSnapshot,
listApiSecretModules,
loadApiSecrets,
@@ -127,6 +135,7 @@ import {
type ApiSecretCheckStatus,
type ApiSecretModuleKey,
type ApiSecretSnapshot,
type ServerProxySnapshot,
type UserApiSecretCheckResult,
} from '@/shared/utils/api-secret-store'
import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview'
@@ -160,6 +169,10 @@ for (const module of modules.value) {
const snapshots = ref<Record<string, ApiSecretSnapshot>>({})
const busy = ref(false)
/** 服务端代理状态:后台代填并锁定时客户端只读。 */
const serverProxy = ref<ServerProxySnapshot | null>(getServerProxySnapshot())
const proxyLocked = computed(() => Boolean(serverProxy.value?.locked && serverProxy.value?.exists))
const proxyUrl = ref('')
const proxyMode = ref<ProxyMode>(1)
const proxyLoading = ref(false)
@@ -255,6 +268,7 @@ function refreshSnapshots() {
ensureModuleState(module.moduleKey)
}
snapshots.value = next
serverProxy.value = getServerProxySnapshot()
}
function snapshotOf(moduleKey: string): ApiSecretSnapshot {
@@ -498,7 +512,7 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
secretsSaved = true
refreshSnapshots()
if (props.showProxy && proxyReady.value && proxyDirty.value) {
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
const api = getPywebviewApi()
if (!api?.save_config) throw new Error('当前客户端未提供代理配置保存能力')
const nextProxyUrl = proxyUrl.value.trim()
@@ -534,11 +548,14 @@ let unsubscribe: (() => void) | null = null
onMounted(() => {
refreshSnapshots()
unsubscribe = subscribeApiSecrets(refreshSnapshots)
void reload()
if (props.showProxy) {
void loadProxyConfig()
void loadBalance()
}
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
void (async () => {
await reload()
if (props.showProxy) {
void loadProxyConfig()
void loadBalance()
}
})()
})
onUnmounted(() => {
@@ -579,6 +596,20 @@ defineExpose({ saveAll, reload })
font-weight: 700;
}
.lock-tag {
display: inline-flex;
align-items: center;
margin-left: 8px;
padding: 1px 8px;
border: 1px solid #6b5a2e;
border-radius: 999px;
background: #2e2a1c;
color: #e6c76a;
font-size: 11px;
font-weight: 600;
vertical-align: middle;
}
.secret-card-desc {
margin-top: 4px;
color: #909ba8;
@@ -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
}
/** 供测试与调试:模块级状态快照。 */
+80
View File
@@ -3,8 +3,10 @@ import assert from 'node:assert/strict'
import { http } from '../src/shared/api/http.ts'
import {
clearApiSecretCache,
getServerProxySnapshot,
getStoredApiSecret,
getStoredApiSecretSnapshot,
listApiSecretModules,
loadApiSecrets,
saveApiSecret,
} from '../src/shared/utils/api-secret-store.ts'
@@ -70,6 +72,26 @@ function bundleResponse(items: unknown[]) {
const LEGACY_MIRROR_KEY = 'brand:api-secret:42:appearance-patent'
/** 桌面桥(pywebview)模拟:后台锁定代理回填本地配置依赖 read_config/save_config。 */
function attachDesktopBridge(
readConfig: () => Record<string, unknown>,
saveConfig: (patch: Record<string, unknown>) => Record<string, unknown>,
) {
const win = (globalThis as Record<string, unknown>).window as Record<string, unknown>
win.pywebview = {
api: { read_config: readConfig, save_config: saveConfig },
}
}
function lockedProxyBundle(proxy: Record<string, unknown>) {
return {
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
requiredModules: ['appearance-patent', 'similar-asin'],
complete: false,
proxy: { ...serverItem('proxy'), ...proxy },
}
}
test('test_secret_store_reads_legacy_value_before_load', () => {
const { localStorage } = setupWindow()
clearApiSecretCache()
@@ -130,3 +152,61 @@ test('test_secret_store_save_rejects_empty_value', async () => {
clearApiSecretCache()
await assert.rejects(() => saveApiSecret('similar-asin', ' '), /密钥不能为空/)
})
test('test_secret_store_locked_proxy_aligns_local_config_once', async (t) => {
setupWindow()
clearApiSecretCache()
const fullUrl = 'https://api.jikip.com/ip-get?num=1&key=abc'
let config: Record<string, unknown> = { proxy_users: { '42': { proxy_url: '', proxy_mode: 2 } } }
const saveCalls: Array<Record<string, unknown>> = []
attachDesktopBridge(
() => config,
(patch) => {
saveCalls.push(patch)
const patchUsers = patch.proxy_users as Record<string, unknown> | undefined
config = {
...config,
...patch,
proxy_users: { ...(config.proxy_users as Record<string, unknown>), ...(patchUsers || {}) },
}
return config
},
)
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) return okResponse({ migrated: 0 })
return okResponse(lockedProxyBundle({ exists: true, locked: true, full: fullUrl, masked: 'https://api.jikip.com' }))
})
await loadApiSecrets({ force: true })
assert.equal(saveCalls.length, 1, '首次加载应把后台锁定代理写入本地配置')
const users = saveCalls[0].proxy_users as Record<string, { proxy_url: string; proxy_mode: number }>
assert.equal(users['42'].proxy_url, fullUrl)
assert.equal(users['42'].proxy_mode, 2, '写入时应保留用户原有的代理模式')
const snapshot = getServerProxySnapshot()
assert.equal(snapshot?.locked, true)
assert.equal(snapshot?.full, fullUrl)
await loadApiSecrets({ force: true })
assert.equal(saveCalls.length, 1, '本地配置已一致时不应重复写入')
})
test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
setupWindow()
clearApiSecretCache()
mockRequest(t, () =>
okResponse(lockedProxyBundle({ exists: true, locked: true, full: 'https://api.jikip.com/ip-get?num=1&key=abc' })),
)
const state = await loadApiSecrets({ force: true })
assert.equal(state, 'incomplete')
assert.equal(getServerProxySnapshot()?.locked, true)
assert.deepEqual(
listApiSecretModules().map((item) => item.moduleKey),
['appearance-patent', 'similar-asin'],
'代理不进模块卡片(不占门禁)',
)
clearApiSecretCache()
assert.equal(getServerProxySnapshot(), null, '登出清理应重置服务端代理状态')
})