feat(密钥设置): 掩码框加眼睛核对,且按键隔离

用户点名:青果 Authpwd 是 •••••••• 且没有任何查看手段,填错只能靠猜。抽
useSecretVisibility(单槽)与 useKeyedSecretVisibility(循环卡用),眼睛按钮件沿用
登录页那对 svg 命名——登录页的 inline 是第一遍抄,这是第二遍,之后只改一处。

按键隔离不是细节:外观专利与货源查询共用同一段循环模板,共用一个布尔会变成
"我核对我手里这把"顺手把用户没打算看的另一把也摊在屏幕上。

射程按用户拍板"一起补":Authpwd、jikip 套餐 key、两张 LLM 密钥卡;弹窗外的
Aliprice 密码不在本面板、未动。三条红线:默认掩码、状态不落 localStorage 不进日志
上报、保存成功/重读配置/切供应商/卸载四处一律收回掩码。

判据:tests/密钥显隐状态机.test.ts 8 支(含"面板里不许再出现没挂眼睛的裸密码框"
这条防复发的尺子)+ tests/mount/密钥面板authpwd显隐.mount.test.ts 6 支。
本面 node --test 994/994、vitest 9 文件 55 例、vue-tsc rc=0。
This commit is contained in:
2026-11-02 16:19:32 +08:00
parent 7e64c12dd6
commit 2cbd99ed4f
6 changed files with 647 additions and 29 deletions
@@ -42,16 +42,23 @@
<div class="secret-field">
<label class="field-label" :for="`secret-input-${module.moduleKey}`">接口密钥</label>
<input
:id="`secret-input-${module.moduleKey}`"
v-model="moduleStates[module.moduleKey].input"
class="secret-input"
type="password"
:placeholder="placeholderOf(module.moduleKey)"
autocomplete="off"
spellcheck="false"
:disabled="busy"
/>
<div class="password-field">
<input
:id="`secret-input-${module.moduleKey}`"
v-model="moduleStates[module.moduleKey].input"
class="secret-input"
:type="llmVisibility.inputTypeOf(module.moduleKey)"
:placeholder="placeholderOf(module.moduleKey)"
autocomplete="off"
spellcheck="false"
:disabled="busy"
/>
<SecretVisibilityToggle
:visible="llmVisibility.visibleOf(module.moduleKey)"
:disabled="busy"
@toggle="llmVisibility.toggle(module.moduleKey)"
/>
</div>
</div>
<div v-if="channelSwitchNeedsValue(module.moduleKey)" class="inline-warn">
@@ -136,21 +143,29 @@
:disabled="busy || proxyLocked"
@input="proxyDirty = true"
/>
<input
v-model="proxyPassword"
class="secret-input"
type="password"
placeholder="Authpwd"
autocomplete="off"
spellcheck="false"
:disabled="busy || proxyLocked"
@input="proxyDirty = true"
/>
<div class="password-field">
<input
v-model="proxyPassword"
class="secret-input"
:type="proxyPasswordType"
placeholder="Authpwd"
autocomplete="off"
spellcheck="false"
:disabled="busy || proxyLocked"
@input="proxyDirty = true"
/>
<SecretVisibilityToggle
:visible="proxyPasswordVisible"
:disabled="busy || proxyLocked"
@toggle="toggleProxyPasswordVisibility"
/>
</div>
</div>
<div class="proxy-plan-hint">
青果没有可填的提取链接:保存时用 Authkey / Authpwd 自动拼出
<code>overseas.proxy.qg.net/get?key=…&amp;format=json</code>(Basic 认证也带在同一条链接里),
本地与后台密钥各存一份。服务端的商标检测用的就是这条链接,不填账密它会按「未配置代理」拦下任务。
Authpwd 默认掩码,点输入框右侧的眼睛可核对;保存成功后自动回到掩码。
</div>
</div>
@@ -178,15 +193,22 @@
/>
</div>
<div class="proxy-plan-row proxy-plan-row--single">
<input
v-model="proxyPlanKey"
class="secret-input"
type="password"
:placeholder="proxyPlanKeyPlaceholder"
autocomplete="off"
spellcheck="false"
:disabled="proxyPlanLoading || proxyPlanSaving"
/>
<div class="password-field">
<input
v-model="proxyPlanKey"
class="secret-input"
:type="planKeyType"
:placeholder="proxyPlanKeyPlaceholder"
autocomplete="off"
spellcheck="false"
:disabled="proxyPlanLoading || proxyPlanSaving"
/>
<SecretVisibilityToggle
:visible="planKeyVisible"
:disabled="proxyPlanLoading || proxyPlanSaving"
@toggle="togglePlanKeyVisibility"
/>
</div>
</div>
<div class="secret-actions">
<button
@@ -285,6 +307,8 @@ import {
userProxyPatch,
} from '@/shared/utils/api-secret-proxy-config'
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
import { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
import SecretVisibilityToggle from '@/shared/components/SecretVisibilityToggle.vue'
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
const props = withDefaults(
@@ -322,6 +346,32 @@ const proxyProvider = ref<ProxyProviderKey>(DEFAULT_PROXY_PROVIDER)
/** 青果隧道端点的代理账密(Authkey/Authpwd):只存本机 app.json,不上报服务端。 */
const proxyAccount = ref('')
const proxyPassword = ref('')
/**
* 面板里每一把"掩码输入"的显隐,同一个出处(2026-11-02 用户点名:填错了看不见,只能靠猜)。
* 眼睛只切自己那一格的 type;状态不落 localStorage、不进日志与上报,
* 重新读取本机配置 / 切供应商 / 保存成功 / 组件卸载全部回到掩码(与「保存成功即清空输入」同一口径)。
*
* LLM 那两把(外观专利/货源查询)共用同一段循环模板 ⇒ 必须按键隔离,
* 否则点一张卡的眼睛会把另一张也摊成明文。
*/
const {
visible: proxyPasswordVisible,
inputType: proxyPasswordType,
toggle: toggleProxyPasswordVisibility,
reset: resetProxyPasswordVisibility,
} = useSecretVisibility()
const {
visible: planKeyVisible,
inputType: planKeyType,
toggle: togglePlanKeyVisibility,
reset: resetPlanKeyVisibility,
} = useSecretVisibility()
const llmVisibility = useKeyedSecretVisibility()
function resetSecretVisibility() {
resetProxyPasswordVisibility()
resetPlanKeyVisibility()
llmVisibility.resetAll()
}
const proxyLoading = ref(false)
const proxyLoadFailed = ref(false)
const proxyReady = ref(false)
@@ -396,6 +446,8 @@ function selectProxyProvider(provider: ProxyProviderKey) {
proxyDirty.value = true
proxyCheckResult.value = null
proxyCheckError.value = ''
// 换的是「哪一家的账密」,明文状态没有理由跟着走过去
resetSecretVisibility()
}
@@ -532,6 +584,8 @@ async function loadProxyConfig() {
proxyLoadFailed.value = false
proxyReady.value = false
proxyDirty.value = false
// 每次重新读取本机配置=换号或重开弹窗:读到的可能就是另一个账号的 Authpwd,不许还亮着明文
resetSecretVisibility()
const api = getPywebviewApi()
proxySupported.value = Boolean(api?.read_config && api?.save_config)
@@ -652,6 +706,9 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
}
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
// 保存成功=账密已落到本机与服务端,界面没有理由还把 Authpwd 亮着明文;
// 失败分支不动(那时用户正需要核对填错在哪一位)。
resetSecretVisibility()
refreshSnapshots()
return true
} catch (error) {
@@ -696,6 +753,8 @@ onMounted(() => {
onUnmounted(() => {
if (unsubscribe) unsubscribe()
// 卸载即回到掩码:弹窗若是 v-show 留着复用,重载路径上不该还显示着上一个账号的明文
resetSecretVisibility()
})
defineExpose({ saveAll, reload })
@@ -0,0 +1,97 @@
<template>
<button
type="button"
class="password-toggle"
:class="{ 'is-visible': visible }"
:aria-pressed="visible"
:aria-label="visible ? '隐藏密码' : '显示密码'"
:disabled="disabled"
@click="emit('toggle')"
>
<svg class="icon-eye" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg>
<svg class="icon-eye-off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="m2 2 20 20"></path>
<path d="M10.733 5.076a10.744 10.744 0 0 1 9.205 6.272 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-1.651 2.59"></path>
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242"></path>
<path d="M17.479 17.499a10.75 10.75 0 0 1-5.479 1.501c-4.478 0-8.268-2.943-9.876-6.652a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 2.646-3.393"></path>
</svg>
</button>
</template>
<script setup lang="ts">
/**
* 密钥输入框的「眼睛」:与登录页 `DesktopLoginPage.vue` 同一组 class 名与同一对 svg 路径,
* 只是从那一页的 inline 收成可复用件(青果 Authpwd 是第一个消费者,其余掩码档以后直接用它,
* 不再各自手搓一份显隐逻辑)。
*
* 本件不认识密钥原文,只有 `visible` 进、`toggle` 出——它改不动绑定值,也发不出请求。
* 配色刻意用 `color: inherit` + 透明度,深浅两套界面都能落(登录页浅、密钥卡深)。
* 定位靠父级的 `position: relative` 容器(口径同登录页的 `.password-field`)。
*/
withDefaults(defineProps<{
/** 当前是否明文(由 `useSecretVisibility()` 提供,本件不自存状态)。 */
visible: boolean
/** 输入框禁用时眼睛一起禁用,免得只读态还能翻出明文。 */
disabled?: boolean
}>(), {
disabled: false,
})
const emit = defineEmits<{ (event: 'toggle'): void }>()
</script>
<style scoped>
.password-toggle {
position: absolute;
top: 50%;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
color: inherit;
background: transparent;
border: 0;
border-radius: 6px;
cursor: pointer;
opacity: .7;
transform: translateY(-50%);
}
.password-toggle:hover:not(:disabled) {
opacity: 1;
}
.password-toggle:focus-visible {
outline: 1px solid currentColor;
outline-offset: 1px;
}
.password-toggle:disabled {
cursor: not-allowed;
opacity: .35;
}
.password-toggle svg {
width: 18px;
height: 18px;
pointer-events: none;
}
.password-toggle .icon-eye-off {
display: none;
}
.password-toggle.is-visible .icon-eye {
display: none;
}
.password-toggle.is-visible .icon-eye-off {
display: block;
}
</style>
@@ -189,6 +189,15 @@
opacity: .72;
}
/* 带「眼睛」的密钥输入框:容器给绝对定位锚,右侧留出不被按钮盖住的空隙(口径同登录页 .password-field)。 */
.password-field {
position: relative;
}
.password-field .secret-input {
padding-right: 48px;
}
.secret-actions {
display: flex;
align-items: center;
@@ -0,0 +1,72 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
/** 密钥输入框的 `type`:默认掩码,只有用户亲自点过眼睛才是 text。 */
export type SecretInputType = 'password' | 'text'
export interface SecretVisibility {
/** 当前是否明文。只活在内存里,随组件实例一起消失。 */
visible: Ref<boolean>
/** 直接绑到输入框 `:type` 的派生值。 */
inputType: ComputedRef<SecretInputType>
/** 眼睛按钮的唯一写入口。 */
toggle: () => void
/** 回到掩码:换供应商/重新读取本机配置/保存成功后都必须叫一次。 */
reset: () => void
}
/**
* 「显示/隐藏这一把密钥」的状态机,单独一个出处(2026-11-02 用户点名青果 Authpwd 没有查看手段)。
* 抽出来的理由与 `NotificationLevelIcon.vue` 一样:写死在模板里就得抄第二遍,
* 而登录页 `DesktopLoginPage.vue` 那份 inline 已经是第一遍——以后只改一处的结局是两处开始不一致。
*
* 三条红线:
* - 默认必须是掩码,明文只在用户点过眼睛之后存在;
* - 这个状态一律不落 localStorage、不进日志与上报(「用户点了显示密码」不是需要上报的事件);
* - 它只管可见性、拿不到也存不住密钥原文,所以切换本身不可能改到绑定值。
*
* 零副作用、零依赖(除 Vue 响应式),`node --test` 可直接测。
*/
export function useSecretVisibility(): SecretVisibility {
const visible = ref(false)
return {
visible,
inputType: computed<SecretInputType>(() => (visible.value ? 'text' : 'password')),
toggle: () => {
visible.value = !visible.value
},
reset: () => {
visible.value = false
},
}
}
export interface KeyedSecretVisibility {
/** 直接绑到循环里那个输入框 `:type`:没点过眼睛的键永远是 password。 */
inputTypeOf: (key: string) => SecretInputType
/** 眼睛图标该画睁眼还是闭眼。 */
visibleOf: (key: string) => boolean
/** 只翻这一个键——「显示外观专利密钥」不该顺手把货源查询那把也亮出来。 */
toggle: (key: string) => void
/** 全回掩码:保存成功、重读本机配置、卸载时都要叫。 */
resetAll: () => void
}
/**
* 循环渲染的密钥卡(外观专利/货源查询共用同一段模板)用的按键显隐。
*
* <p>为什么不能复用上面那个单槽位:单槽一共享,点一张卡的眼睛会把**所有**卡都变明文,
* 那是"我只核对我手里这把"这个动作被放大成"把用户没打算看的两把也摊在屏幕上"。</p>
*/
export function useKeyedSecretVisibility(): KeyedSecretVisibility {
const visibleByKey = ref<Record<string, boolean>>({})
return {
inputTypeOf: (key: string) => (visibleByKey.value[key] ? 'text' : 'password'),
visibleOf: (key: string) => visibleByKey.value[key] === true,
toggle: (key: string) => {
visibleByKey.value = { ...visibleByKey.value, [key]: !visibleByKey.value[key] }
},
resetAll: () => {
visibleByKey.value = {}
},
}
}
@@ -0,0 +1,270 @@
/**
* 密钥设置面板「青果 Authpwd 眼睛」的挂载用例(2026-11-02 用户看图点名:Authkey 是明文可见的,
* Authpwd 却是 •••••••• 且没有任何查看手段,填错了只能靠猜)。
*
* 五组靶子:
* ① 默认掩码,点眼睛变明文,再点回掩码(`useSecretVisibility` 的两态开关在界面上真的成立);
* ② 切换眼睛**不动绑定值**、**不产生改动标记**、**不发保存/送检请求**(点一下眼睛就冒出
* 「检测输入账密(未保存)」=把可见性误判成用户改了代理);
* ③ 眼睛只管 Authpwd 这一格:Authkey 照旧明文、各模块密钥照旧掩码,不做全站唯一的特例化扩散;
* ④ 保存成功即回到掩码(沿用该面板「保存成功即清空输入」的口径),且输入值不丢;
* ⑤ 卸载后重新挂载(重开弹窗/换号后重读配置)不得留一个还显示着明文的重载路径。
*
* ⚠ 用例里的账密一律是假值(fakekey/fakepwd),真实凭据不得进任何跟踪件。
*
* 跑法:`npx vitest run tests/mount/密钥面板authpwd显隐.mount.test.ts`
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
const UID = '1301'
const FAKE_KEY = 'fakekey'
const FAKE_PWD = 'fakepwd'
const message = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
success: vi.fn(),
info: vi.fn(),
}))
const store = vi.hoisted(() => ({
checkApiSecret: vi.fn(),
clearApiSecret: vi.fn(),
getServerProxySnapshot: vi.fn(),
getStoredApiSecretSnapshot: vi.fn(),
listApiSecretModules: vi.fn(),
loadApiSecrets: vi.fn(),
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
deleteMyApiSecret: vi.fn(),
fetchProxyPlan: vi.fn(),
saveProxyPlan: vi.fn(),
clearProxyPlan: vi.fn(),
}))
const bridge = vi.hoisted(() => ({
readConfig: vi.fn(),
saveConfig: vi.fn(),
}))
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/utils/api-secret-store', () => ({
checkApiSecret: store.checkApiSecret,
clearApiSecret: store.clearApiSecret,
getServerProxySnapshot: store.getServerProxySnapshot,
getStoredApiSecretSnapshot: store.getStoredApiSecretSnapshot,
listApiSecretModules: store.listApiSecretModules,
loadApiSecrets: store.loadApiSecrets,
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
deleteMyApiSecret: secretApi.deleteMyApiSecret,
fetchProxyPlan: secretApi.fetchProxyPlan,
saveProxyPlan: secretApi.saveProxyPlan,
clearProxyPlan: secretApi.clearProxyPlan,
}))
vi.mock('@/shared/bridges/pywebview', () => ({
getPywebviewApi: () => ({ read_config: bridge.readConfig, save_config: bridge.saveConfig }),
}))
function emptySnapshot() {
return {
value: '', masked: '', channel: '', exists: false, locked: false,
checkStatus: 'unknown', checkCode: '', checkMessage: '',
checkLatencyMs: null, checkedAt: null, updatedAt: null,
}
}
/** 本机已存过青果账密(proxy_users[uid]):桌面桥读得到的就是这份。 */
function qingguoConfig() {
return {
proxy_users: {
[UID]: {
proxy_url: '', proxy_mode: 2, proxy_provider: 'qingguo',
proxy_account: FAKE_KEY, proxy_password: FAKE_PWD,
},
},
}
}
function checkResult(over: Record<string, unknown> = {}) {
return {
moduleKey: 'proxy',
checkStatus: 'passed',
checkCode: 'ok',
checkMessage: '连通正常',
checkLatencyMs: 120,
checkedAt: null,
viaProxy: false,
...over,
}
}
let wrapper: VueWrapper | null = null
async function mountPanel() {
wrapper = mount(ApiSecretSettingsPanel)
await flushPromises()
await flushPromises()
return wrapper
}
/** 代理是最后一张卡。 */
function proxyCard(panel: VueWrapper) {
const cards = panel.findAll('.secret-card')
return cards[cards.length - 1]
}
/** 青果账密那一行:[0]=Authkey、[1]=Authpwd。 */
function accountInput(panel: VueWrapper) {
return proxyCard(panel).findAll('input')[0]
}
function passwordInput(panel: VueWrapper) {
return proxyCard(panel).findAll('input')[1]
}
function eyeButton(panel: VueWrapper) {
return proxyCard(panel).find('.password-toggle')
}
/** 读输入框当前值:VTU 的 DOMWrapper 上没有取值的语法糖,别拿 text() 冒充。 */
function valueOf(node: { element: Element }) {
return (node.element as HTMLInputElement).value
}
function proxyCheckButton(panel: VueWrapper) {
return proxyCard(panel).findAll('.check-btn')[0]
}
async function saveAll(panel: VueWrapper, options: { requireAll?: boolean } = {}) {
const exposed = panel.vm as unknown as { saveAll: (o?: { requireAll?: boolean }) => Promise<boolean> }
const saved = await exposed.saveAll(options)
await flushPromises()
await flushPromises()
return saved
}
beforeEach(() => {
localStorage.clear()
localStorage.setItem('uid', UID)
vi.clearAllMocks()
store.listApiSecretModules.mockReturnValue([
{ moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
{ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
])
store.getStoredApiSecretSnapshot.mockReturnValue(emptySnapshot())
store.getServerProxySnapshot.mockReturnValue(null)
store.subscribeApiSecrets.mockReturnValue(() => undefined)
store.loadApiSecrets.mockResolvedValue('complete')
store.checkApiSecret.mockResolvedValue(checkResult())
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
secretApi.putMyApiSecret.mockResolvedValue({})
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
bridge.saveConfig.mockResolvedValue(undefined)
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
describe('Authpwd 眼睛:两态切换', () => {
it('默认掩码,点一次变明文,再点一次回掩码', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
expect(pwd.attributes('type')).toBe('password')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type'), '点眼睛就是把这一格的 type 换掉').toBe('text')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('true')
expect(eyeButton(panel).attributes('aria-label')).toBe('隐藏密码')
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type')).toBe('password')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
})
it('切换眼睛不动绑定值、不记成改动、也不发保存或送检请求', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
const storageKeys = Object.keys(localStorage)
await eyeButton(panel).trigger('click')
await eyeButton(panel).trigger('click')
await flushPromises()
expect(valueOf(pwd), '可见性切换不该吃掉一个字符').toBe(FAKE_PWD)
expect(valueOf(accountInput(panel))).toBe(FAKE_KEY)
expect(proxyCheckButton(panel).text(), '点眼睛不等于「改了代理」:按钮不许开始自称检的是未保存输入值')
.toContain('检测配置代理')
expect(store.checkApiSecret).not.toHaveBeenCalled()
expect(bridge.saveConfig).not.toHaveBeenCalled()
expect(secretApi.putMyApiSecret).not.toHaveBeenCalled()
expect(Object.keys(localStorage), '「用户点了显示密码」不配拥有一个持久化键').toEqual(storageKeys)
})
it('只切 Authpwd 这一格:Authkey 照旧明文、模块密钥照旧掩码', async () => {
const panel = await mountPanel()
await eyeButton(panel).trigger('click')
expect(passwordInput(panel).attributes('type')).toBe('text')
expect(accountInput(panel).attributes('type')).toBe('text')
for (const card of panel.findAll('.secret-card').slice(0, -1)) {
expect(card.find('input').attributes('type'), '别的密钥不跟着这次改动放开').toBe('password')
}
})
})
describe('Authpwd 眼睛:复位口径', () => {
it('保存成功后回到掩码,且账密输入值不丢', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type')).toBe('text')
await pwd.setValue(`${FAKE_PWD}Z`)
expect(await saveAll(panel)).toBe(true)
expect(bridge.saveConfig).toHaveBeenCalledTimes(1)
expect(pwd.attributes('type'), '保存成功=配置已落地,界面没理由还亮着明文').toBe('password')
expect(valueOf(pwd)).toBe(`${FAKE_PWD}Z`)
})
it('卸载后重新挂载(重开弹窗/换号重读配置)不带出明文', async () => {
const first = await mountPanel()
await eyeButton(first).trigger('click')
expect(passwordInput(first).attributes('type')).toBe('text')
first.unmount()
const again = await mountPanel()
expect(passwordInput(again).attributes('type')).toBe('password')
expect(eyeButton(again).attributes('aria-pressed')).toBe('false')
expect(valueOf(passwordInput(again)), '重读到的还是那把假密码,只是重新盖上').toBe(FAKE_PWD)
})
it('后台锁定代理时眼睛跟着输入框一起禁用', async () => {
store.getServerProxySnapshot.mockReturnValue({
...emptySnapshot(), exists: true, locked: true, channel: 'qingguo', full: '',
})
const panel = await mountPanel()
expect(passwordInput(panel).attributes('disabled')).toBeDefined()
expect(eyeButton(panel).attributes('disabled'), '只读态不该还能把明文翻出来').toBeDefined()
})
})
@@ -0,0 +1,111 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve, dirname } from 'node:path'
import { useKeyedSecretVisibility, useSecretVisibility } from '../src/shared/composables/useSecretVisibility.ts'
const here = dirname(fileURLToPath(import.meta.url))
const repoRoot = resolve(here, '..')
/** 去掉注释再扫出口:注释里写「不落 localStorage」是说明,不是真的存储调用。 */
function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
}
/**
* 密钥输入框「眼睛」的状态机(2026-11-02 用户点名:青果 Authpwd 是 •••••••• 且没有查看手段)。
* 判的是这台状态本身的形状;它落到界面上的行为在 tests/mount/密钥面板authpwd显隐.mount.test.ts。
*/
test('默认掩码,点一次眼睛变明文,再点一次回掩码', () => {
const visibility = useSecretVisibility()
const seen: string[] = []
for (let i = 0; i < 3; i += 1) {
seen.push(visibility.inputType.value)
visibility.toggle()
}
assert.deepEqual(seen, ['password', 'text', 'password'], '眼睛必须是自复位的两态开关,不能越点越亮')
})
test('reset 一律回到掩码(换号/重读配置/保存成功都走它),且重复调用不改变语义', () => {
const visibility = useSecretVisibility()
assert.equal(visibility.inputType.value, 'password')
visibility.toggle()
assert.equal(visibility.inputType.value, 'text')
visibility.reset()
assert.equal(visibility.inputType.value, 'password', 'reset 后必须掩码')
visibility.reset()
assert.equal(visibility.inputType.value, 'password', 'reset 幂等:不能把掩码翻成明文')
// 复位后眼睛仍可用(下一次点击还是明文,不是卡死在掩码)
visibility.toggle()
assert.equal(visibility.inputType.value, 'text')
})
test('状态机只交出可见性,不交出任何能带走密钥原文的口子', () => {
const visibility = useSecretVisibility()
assert.deepEqual(
Object.keys(visibility).sort(),
['inputType', 'reset', 'toggle', 'visible'],
'成员集固定:多一个口子就多一条把原文带进日志/上报的路',
)
visibility.toggle()
assert.equal(typeof visibility.visible.value, 'boolean')
assert.ok(visibility.inputType.value === 'text' || visibility.inputType.value === 'password')
})
test('显隐状态不落本机存储、不进日志、不发上报', () => {
const source = stripComments(readFileSync(
resolve(repoRoot, 'src/shared/composables/useSecretVisibility.ts'),
'utf-8',
))
for (const outlet of [
'localStorage', 'sessionStorage', 'indexedDB', 'document.cookie', 'caches',
'console.', 'fetch(', 'XMLHttpRequest', 'sendBeacon', 'WebSocket',
]) {
assert.ok(!source.includes(outlet), `状态机里不该出现出口 ${outlet}:把「用户点了显示密码」变成持久态或事件是没必要的隐私面`)
}
})
test('眼睛按钮件自己也不留第二条持久化/上报出口', () => {
const source = stripComments(readFileSync(
resolve(repoRoot, 'src/shared/components/SecretVisibilityToggle.vue'),
'utf-8',
))
for (const outlet of ['localStorage', 'sessionStorage', 'console.', 'fetch(', 'sendBeacon']) {
assert.ok(!source.includes(outlet), `眼睛按钮不该出现出口 ${outlet}:它只 emit('toggle')`)
}
assert.match(source, /\$emit\('toggle'\)|emit\('toggle'\)/, '唯一的对外动作就是 toggle')
})
test('按键显隐:点一张卡的眼睛不许把另一张也摊成明文', () => {
const keyed = useKeyedSecretVisibility()
assert.equal(keyed.inputTypeOf('appearance-patent'), 'password', '未知键必须默认掩码')
keyed.toggle('appearance-patent')
assert.equal(keyed.inputTypeOf('appearance-patent'), 'text')
assert.equal(keyed.visibleOf('appearance-patent'), true)
assert.equal(keyed.inputTypeOf('goods-source'), 'password', '隔壁那张卡不许跟着亮')
assert.equal(keyed.visibleOf('goods-source'), false)
})
test('resetAll 把所有键一次收回掩码(保存成功/重读配置/卸载都走它)', () => {
const keyed = useKeyedSecretVisibility()
keyed.toggle('appearance-patent')
keyed.toggle('goods-source')
keyed.resetAll()
assert.deepEqual(
[keyed.inputTypeOf('appearance-patent'), keyed.inputTypeOf('goods-source')],
['password', 'password'],
)
keyed.resetAll()
assert.equal(keyed.inputTypeOf('appearance-patent'), 'password', '重复 resetAll 不许翻转成明文')
})
test('面板里不许再出现没挂眼睛的裸密码框', () => {
const source = stripComments(readFileSync(
resolve(repoRoot, 'src/shared/components/ApiSecretSettingsPanel.vue'),
'utf-8',
))
assert.ok(!/type="password"/.test(source),
'又留下一个 •••• 且没有查看手段的字段(本会话用户点名的就是这个形状)⇒ 新密码框必须走 useSecretVisibility / useKeyedSecretVisibility')
const toggles = (source.match(/<SecretVisibilityToggle/g) || []).length
assert.ok(toggles >= 3, `面板里 Authpwd/套餐 key/LLM 循环都该有眼睛,实际只数到 ${toggles} 个`)
})