fix(cr2-frontend): 代理归属回退、换号继承确认与请求竞态收口

- CR-04:全局代理加 proxy_uid 归属,跨账号不再静默回退/补报
- CR-12:取消静默继承,设置页显式确认;同 OS 作用域、locked 代理排除、无效快照清除、uid+epoch 双校验、登出 capture 超时
- CR-26/27:关键词分页初始值与档位一致;两页面请求序号闸丢弃旧响应

vue-tsc 两前端 rc=0;定向 35 + 8 + 2 例全绿。
This commit is contained in:
2026-10-26 11:33:37 +08:00
parent b5e4c45add
commit b963561043
16 changed files with 1245 additions and 136 deletions
@@ -10,6 +10,7 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm'
import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import {
GATING_COUNTRIES,
GATING_SOURCES,
@@ -50,6 +51,10 @@ const batchText = ref('')
const importBusy = ref(false)
const busyRowId = ref(0)
// 快速改筛选/翻页时先发的请求可能后返回;列表与统计各一个序号闸(CR-27)
const pageGate = createLatestRequestGate()
const statsGate = createLatestRequestGate()
const countryOptions = GATING_COUNTRIES.filter((country) => country !== '全部')
const typeOptions = GATING_TYPES
@@ -72,30 +77,37 @@ function feedback(message: string, kind: AdminFeedbackKind): void {
}
async function loadStats(): Promise<void> {
const token = statsGate.begin()
statsLoading.value = true
statsError.value = ''
try {
stats.value = await fetchBrandGatingStats()
const result = await fetchBrandGatingStats()
if (!statsGate.isCurrent(token)) return
stats.value = result
} catch (error) {
if (!statsGate.isCurrent(token)) return
statsError.value = actionableErrorText(error)
} finally {
statsLoading.value = false
if (statsGate.isCurrent(token)) statsLoading.value = false
}
}
async function loadPage(nextPage = page.value): Promise<void> {
const token = pageGate.begin()
pageLoading.value = true
loadError.value = ''
try {
const result = await fetchBrandGatingPage(filter, nextPage, pageSize.value)
if (!pageGate.isCurrent(token)) return
rows.value = result.rows
total.value = result.total
page.value = nextPage
loaded.value = true
} catch (error) {
if (!pageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
pageLoading.value = false
if (pageGate.isCurrent(token)) pageLoading.value = false
}
}
@@ -10,7 +10,9 @@ import { useCompanyTabStore } from '@/stores/company-tab'
import { actionableErrorText } from '@/components/admin-feedback'
import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import {
KEYWORD_USAGE_PAGE_SIZE,
KEYWORD_USAGE_SCENES,
createKeywordUsageFilter,
keywordUsageCountsText,
@@ -40,16 +42,21 @@ const overviewLoading = ref(false)
const usageRows = ref<KeywordUsageRow[]>([])
const usageTotal = ref(0)
const usagePage = ref(1)
const usagePageSize = ref(15)
const usagePageSize = ref(KEYWORD_USAGE_PAGE_SIZE)
const usageCounts = ref<KeywordUsageCounts>({ copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 })
const usageLoading = ref(false)
const deleteRows = ref<KeywordUsageRow[]>([])
const deleteTotal = ref(0)
const deletePage = ref(1)
const deletePageSize = ref(15)
const deletePageSize = ref(KEYWORD_USAGE_PAGE_SIZE)
const deleteLoading = ref(false)
// 切公司/快速改筛选时,先发的请求可能后返回;每个加载口径各一个序号闸(CR-27)
const overviewGate = createLatestRequestGate()
const usageGate = createLatestRequestGate()
const deleteGate = createLatestRequestGate()
const statsCards = computed(() => {
const stats = overview.value?.stats
return [
@@ -76,42 +83,52 @@ function queryParams() {
}
async function loadOverview(): Promise<void> {
const token = overviewGate.begin()
overviewLoading.value = true
try {
overview.value = await fetchKeywordUsageOverview({ companyId: companyTab.requestCompanyId })
const result = await fetchKeywordUsageOverview({ companyId: companyTab.requestCompanyId })
if (!overviewGate.isCurrent(token)) return
overview.value = result
} catch (error) {
if (!overviewGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
overviewLoading.value = false
if (overviewGate.isCurrent(token)) overviewLoading.value = false
}
}
async function loadUsage(page = usagePage.value): Promise<void> {
const token = usageGate.begin()
usageLoading.value = true
try {
const result = await fetchKeywordUsage({ ...queryParams(), page, pageSize: usagePageSize.value })
if (!usageGate.isCurrent(token)) return
usageRows.value = result.rows
usageTotal.value = result.total
usageCounts.value = result.counts
usagePage.value = page
} catch (error) {
if (!usageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
usageLoading.value = false
if (usageGate.isCurrent(token)) usageLoading.value = false
}
}
async function loadDeletes(page = deletePage.value): Promise<void> {
const token = deleteGate.begin()
deleteLoading.value = true
try {
const result = await fetchKeywordUsageDeletes({ ...queryParams(), page, pageSize: deletePageSize.value })
if (!deleteGate.isCurrent(token)) return
deleteRows.value = result.rows
deleteTotal.value = result.total
deletePage.value = page
} catch (error) {
if (!deleteGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
deleteLoading.value = false
if (deleteGate.isCurrent(token)) deleteLoading.value = false
}
}
@@ -55,6 +55,9 @@ export interface KeywordUsageOverview {
export const KEYWORD_USAGE_SCENES = ['已使用', '添加关键词'] as const
/** 初始每页条数:必须落在 OldPagination 的档位(10/20/50/100)里(CR-26)。 */
export const KEYWORD_USAGE_PAGE_SIZE = 10
export function createKeywordUsageFilter(): KeywordUsageFilter {
return { user: '', country: '', keyword: '', scene: '' }
}
@@ -0,0 +1,27 @@
/**
* 只让最后一次请求落地(CR-27)。
*
* 快速切公司/筛选时,先发的请求可能后返回;如果直接写 ref,旧响应会覆盖新结果。
* 每个加载函数在发请求前 `begin()` 拿一个 token,回写前 `isCurrent(token)` 验一次;
* 新请求一发出,旧 token 立即作废(不需要 AbortController 也能丢掉晚到的响应)。
*/
export interface LatestRequestGate {
/** 开一次新请求并作废之前所有 token(含未返回的那些)。 */
begin(): number
/** 这个 token 是否仍是最后一次 `begin()` 发出的。 */
isCurrent(token: number): boolean
}
export function createLatestRequestGate(): LatestRequestGate {
let latest = 0
return {
begin(): number {
latest += 1
return latest
},
isCurrent(token: number): boolean {
// token 只由 begin() 发出(从 1 起);0 不是合法 token,避免未发请求时误判为当前
return token > 0 && token === latest
},
}
}
@@ -1,6 +1,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
KEYWORD_USAGE_PAGE_SIZE,
createKeywordUsageFilter,
keywordUsageCountsText,
keywordUsageSceneLabel,
@@ -8,6 +9,12 @@ import {
parseKeywordUsagePage,
} from '../src/pages/tasks/keyword-usage-model.ts'
test('keyword_usage_default_page_size_matches_pagination_options', () => {
// OldPagination 的档位是 10/20/50/100;初始值不在档位里时下拉显示与实际请求不一致(CR-26)
assert.equal(KEYWORD_USAGE_PAGE_SIZE, 10)
assert.ok([10, 20, 50, 100].includes(KEYWORD_USAGE_PAGE_SIZE))
})
test('keyword_usage_filter_defaults_and_scene_labels', () => {
assert.deepEqual(createKeywordUsageFilter(), { user: '', country: '', keyword: '', scene: '' })
assert.equal(keywordUsageSceneLabel('复制关键词'), '已使用(复制)')
@@ -0,0 +1,21 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createLatestRequestGate } from '../src/utils/latest-request.ts'
test('latest_request_gate_only_accepts_the_newest_token', () => {
const gate = createLatestRequestGate()
const first = gate.begin()
assert.equal(gate.isCurrent(first), true)
const second = gate.begin()
assert.equal(gate.isCurrent(second), true)
assert.equal(gate.isCurrent(first), false, '新请求一发出,旧 token 必须立即失效')
})
test('latest_request_gate_starts_with_no_current_token', () => {
const gate = createLatestRequestGate()
assert.equal(gate.isCurrent(0), false, '未发请求前不能用 0 号 token 回写')
const token = gate.begin()
assert.ok(token > 0)
assert.equal(gate.isCurrent(token), true)
})
@@ -0,0 +1,201 @@
/**
* 切公司/快速改筛选时,旧响应不得覆盖新结果(CR-27)。
*
* 跑真组件 + 真 pinia store,API 用可控 deferred 顶掉:
* 先让新请求落地,再让旧请求后返回,断言页面仍显示新结果。
*
* 跑法:`npx vitest run tests/mount/stale-response-drop.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import KeywordUsagePage from '@/pages/tasks/KeywordUsagePage.vue'
import BrandGatingPanel from '@/pages/tasks/BrandGatingPanel.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const keywordApi = vi.hoisted(() => ({
fetchKeywordUsage: vi.fn(),
fetchKeywordUsageDeletes: vi.fn(),
fetchKeywordUsageOverview: vi.fn(),
}))
const gatingApi = vi.hoisted(() => ({
fetchBrandGatingPage: vi.fn(),
fetchBrandGatingStats: vi.fn(),
deleteBrandGating: vi.fn(),
importBrandGatingText: vi.fn(),
submitBrandGating: vi.fn(),
updateBrandGatingStatus: vi.fn(),
}))
vi.mock('@/pages/tasks/keyword-usage-api.ts', () => keywordApi)
vi.mock('@/pages/tasks/brand-gating-api.ts', () => gatingApi)
interface Deferred<T> {
promise: Promise<T>
resolve: (value: T) => void
}
function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void
const promise = new Promise<T>((done) => {
resolve = done
})
return { promise, resolve }
}
const loadingDirective = { mounted() {}, updated() {} }
function mountPage(component: Parameters<typeof mount>[0], pinia: Pinia): VueWrapper {
return mount(component, {
global: {
plugins: [pinia],
directives: { loading: loadingDirective },
},
})
}
function usagePage(keyword: string) {
return {
total: 1,
rows: [{
userName: 'alice',
country: '英国',
keyword,
scene: '复制关键词',
time: '2026-10-25 10:00:00',
}],
counts: { copy: 1, copyExisting: 1, copyDeleted: 0, add: 0 },
}
}
function gatingPage(brand: string) {
return {
total: 1,
rows: [{
id: 1,
brand,
asin: '',
country: '英国',
gatingType: '品牌gating',
status: 1,
source: 'MANUAL',
shopName: '',
remark: '',
createdAt: '2026-10-25 10:00:00',
updatedAt: '',
disabledAt: '',
}],
}
}
describe('CR-27:切换期间晚到的响应必须丢弃', () => {
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
// 只有超管才带 company_id;company tab 的 activeId 直接改,不依赖公司目录接口
useCompanyTabStore().setActiveId(1)
keywordApi.fetchKeywordUsageOverview.mockResolvedValue({
stats: { used: 0, exist: 0, deletedKw: 0, added: 0, totalUse: 0, deletes: 0 },
users: [],
countries: [],
})
keywordApi.fetchKeywordUsageDeletes.mockResolvedValue({
total: 0,
rows: [],
counts: { copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 },
})
gatingApi.fetchBrandGatingStats.mockResolvedValue({
total: 0,
active: 0,
disabled: 0,
brands: 0,
byType: [],
byCountry: [],
bySource: [],
})
})
it('关键词使用记录:切公司后旧公司响应后到,页面仍显示新公司数据', async () => {
const calls: Array<{
companyId?: number | null
pageSize?: number
deferred: Deferred<ReturnType<typeof usagePage>>
}> = []
keywordApi.fetchKeywordUsage.mockImplementation((params: { companyId?: number | null; pageSize?: number }) => {
const pending = deferred<ReturnType<typeof usagePage>>()
calls.push({ companyId: params.companyId, pageSize: params.pageSize, deferred: pending })
return pending.promise
})
const wrapper = mountPage(KeywordUsagePage, pinia)
await flushPromises()
expect(calls).toHaveLength(1)
expect(calls[0].companyId).toBe(1)
expect(calls[0].pageSize).toBe(10)
useCompanyTabStore().setActiveId(2)
await flushPromises()
expect(calls).toHaveLength(2)
expect(calls[1].companyId).toBe(2)
calls[1].deferred.resolve(usagePage('beta-keyword'))
await flushPromises()
expect(wrapper.text()).toContain('beta-keyword')
// 旧公司的响应晚到:序号闸必须把它丢掉
calls[0].deferred.resolve(usagePage('alpha-keyword'))
await flushPromises()
expect(wrapper.text()).toContain('beta-keyword')
expect(wrapper.text()).not.toContain('alpha-keyword')
})
it('品牌 Gating:快速改筛选时旧筛选响应后到,列表仍显示新筛选结果', async () => {
const calls: Array<{
keyword: string
deferred: Deferred<ReturnType<typeof gatingPage>>
}> = []
gatingApi.fetchBrandGatingPage.mockImplementation((filter: { keyword: string }) => {
const pending = deferred<ReturnType<typeof gatingPage>>()
calls.push({ keyword: filter.keyword, deferred: pending })
return pending.promise
})
const wrapper = mountPage(BrandGatingPanel, pinia)
await flushPromises()
expect(calls).toHaveLength(1)
calls[0].deferred.resolve(gatingPage('initial-brand'))
await flushPromises()
expect(wrapper.text()).toContain('initial-brand')
const input = wrapper.get('input[placeholder="搜索品牌 / ASIN"]')
const queryButton = wrapper.findAll('button').find((button) => button.text() === '查询')
expect(queryButton, '页面里应有「查询」按钮').toBeDefined()
await input.setValue('old')
await queryButton!.trigger('click')
await flushPromises()
expect(calls).toHaveLength(2)
expect(calls[1].keyword).toBe('old')
await input.setValue('new')
await queryButton!.trigger('click')
await flushPromises()
expect(calls).toHaveLength(3)
expect(calls[2].keyword).toBe('new')
calls[2].deferred.resolve(gatingPage('new-brand'))
await flushPromises()
expect(wrapper.text()).toContain('new-brand')
calls[1].deferred.resolve(gatingPage('old-brand'))
await flushPromises()
expect(wrapper.text()).toContain('new-brand')
expect(wrapper.text()).not.toContain('old-brand')
})
})
@@ -102,8 +102,8 @@
<span>自动登录</span>
</label>
</div>
<button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn">
{{ loggingIn ? '登录中...' : '登录' }}
<button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn || logoutCleanupPending">
{{ loggingIn ? '登录中...' : logoutCleanupPending ? '正在退出...' : '登录' }}
</button>
</form>
</div>
@@ -136,6 +136,11 @@ const username = ref('')
const password = ref('')
const passwordVisible = ref(false)
const loggingIn = ref(false)
/**
* 登出清理进行中(CR-12):继承快照 capture 有超时,但等它返回前不能允许再提交登录,
* 否则新账号 B 的 token/uid 会被上一轮 clearSignedOutState 删掉。
*/
const logoutCleanupPending = ref(false)
const errorMessage = ref('')
const kickedNotice = ref(false)
const expiredNotice = ref(false)
@@ -407,7 +412,8 @@ function toggleUpdate() {
}
async function submitLogin() {
if (loggingIn.value) return
// 登出清理未完成时禁止提交:清理函数会删 token/uid,晚到的登录会被它清掉(CR-12)
if (loggingIn.value || logoutCleanupPending.value) return
const account = username.value.trim()
if (!account || !password.value) {
errorMessage.value = '请输入账号和密码'
@@ -480,7 +486,9 @@ async function submitLogin() {
onMounted(() => {
const params = new URLSearchParams(window.location.search || '')
if (params.get('logout') === '1' || params.get('switch') === '1') {
logoutCleanupPending.value = true
const clearSignedOutState = () => {
logoutCleanupPending.value = false
// 清缓存必须在移除 uid 之前:镜像键带 uid,反序会按 uid=0 删错位置,
// 把本账号的明文镜像留在磁盘上给下一个账号(或网页脚本)读到。
clearApiSecretCache()
@@ -33,14 +33,18 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
import NotificationBell from '@/shared/components/NotificationBell.vue'
import {
confirmApiSecretInheritance,
declineApiSecretInheritance,
getPendingApiSecretInheritance,
getStoredApiSecretSnapshot,
listApiSecretModules,
loadApiSecrets,
takeApiSecretInheritanceNotice,
type ApiSecretInheritanceNotice,
type ApiSecretModuleKey,
} from '@/shared/utils/api-secret-store'
@@ -51,22 +55,71 @@ const submitting = ref(false)
const username = ref('')
const hint = ref('填写密钥后请先点「检测」确认可用再保存(检测通过的输入值保存时会沿用同一结果),全部检测通过后即可进入工具台。')
function inheritanceLabels(moduleKeys: string[], proxy: boolean): string[] {
const labels = listApiSecretModules()
.filter((module) => moduleKeys.includes(module.moduleKey))
.map((module) => module.moduleLabel)
if (proxy) labels.push('代理设置')
return labels
}
function showInheritanceNotice(inherited: ApiSecretInheritanceNotice | null): void {
if (!inherited) return
const labels = inheritanceLabels(inherited.moduleKeys, inherited.proxy)
// 共享电脑上不把上一个账号的用户名展示给新账号(CR-12)
hint.value = labels.length
? `已继承本机上一个账号的${labels.join('、')},请点击上方对应模块的「检测」确认后保存进入。`
: '已继承本机上一个账号的密钥配置,请点击上方「检测」逐项确认后保存进入。'
}
/**
* 继承确认(CR-12):同机换号不再静默继承上一个账号的密钥/代理。
* 只在本机确实有快照、且当前账号服务端还有空缺时弹一次确认;取消即清快照。
*/
async function promptPendingInheritance(): Promise<void> {
const pending = getPendingApiSecretInheritance()
if (!pending) {
showInheritanceNotice(takeApiSecretInheritanceNotice())
return
}
const labels = inheritanceLabels(pending.moduleKeys, pending.proxy)
const detail = labels.length ? `留下的${labels.join('、')}` : '留下的密钥配置'
const confirmed = () => {
void confirmApiSecretInheritance().then((notice) => {
if (!notice) {
hint.value = '未继承:服务端已有的项不会被覆盖,请手动填写并检测本账号密钥。'
return
}
showInheritanceNotice(notice)
})
}
const declined = () => {
void declineApiSecretInheritance().then(() => {
hint.value = '已跳过本机配置继承,请填写当前账号自己的密钥并检测后保存进入。'
})
}
// 两参 then:取消/关闭只走拒绝分支,不会把「确认过程中的网络失败」误当成用户拒绝而清快照
void ElMessageBox.confirm(
`检测到本机上一个账号${detail}。是否导入到当前账号?`
+ '仅在同一台电脑、同一 Windows 用户下、且确认这是你自己的配置时才选择「继承」;'
+ '服务端已有的密钥/代理不会被覆盖,后台锁定的代理也不会继承。',
'本机配置继承确认',
{
type: 'warning',
confirmButtonText: '继承',
cancelButtonText: '不继承',
distinguishCancelAndClose: true,
},
).then(confirmed, declined)
}
onMounted(() => {
try {
username.value = window.localStorage.getItem('username') || ''
} catch {
/* 忽略存储异常 */
}
const inherited = takeApiSecretInheritanceNotice()
if (inherited) {
const labels = listApiSecretModules()
.filter((module) => inherited.moduleKeys.includes(module.moduleKey))
.map((module) => module.moduleLabel)
if (inherited.proxy) labels.push('代理设置')
hint.value = labels.length
? `已继承本机账号「${inherited.fromUsername || inherited.fromUid}」的${labels.join('、')},请点击上方对应模块的「检测」确认后保存进入。`
: `已继承本机账号「${inherited.fromUsername || inherited.fromUid}」的密钥配置,请点击上方「检测」逐项确认后保存进入。`
}
void promptPendingInheritance()
})
/**
@@ -74,7 +74,14 @@ export interface DesktopConfigUpdate {
proxy_url?: string;
proxy_mode?: ProxyMode;
current_uid?: string;
/** 全局 proxy_url 的归属 uid(CR-04:只有 owner 匹配才允许回退)。 */
proxy_uid?: string;
/** 显式共享白名单:整机共享或指定 uid 列表(CR-04)。 */
proxy_shared?: boolean;
proxy_shared_uids?: string[];
proxy_users?: Record<string, { proxy_url?: string; proxy_mode?: number }>;
/** 本机继承快照的作用域标记(CR-12:同一 app.json 才能继承)。 */
api_secret_os_scope?: string;
/** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */
api_secret_inherit?: Record<string, unknown> | null;
aliprice_usename?: string;
@@ -1,11 +1,20 @@
/**
* 本机账号切换时的密钥继承:A 登出时留快照,B 登录后只补 B 服务端空缺的模块。
* 本机账号切换时的密钥继承:A 登出时留快照,B 登录后**经用户显式确认**只补 B 服务端空缺的模块。
*
* 安全口径(CR-12):
* - 不再静默继承:doLoad 只把可继承的快照登记成 pending,必须由设置页确认后才调 migrate;
* - 同 OS 用户限制:快照只从桌面原生 app.json 读,且带 `osUserScope`(该文件自己的作用域标记)。
* 作用域缺失/不一致(例如把别的 Windows 用户的 app.json 拷过来)一律视为无效并清键;
* - 后台锁定的代理不参与继承:服务端已锁定时客户端不得再用上一个账号的出口;
* - 无效/过期(>30 天)/结构不符的快照立即从 app.json 清掉,不让明文密钥无限期留在本机;
* - 每个 await 之后都比 uid 与 epoch:登出/切号期间晚到的响应不得写进新账号。
*
* 这里不直接读写密钥镜像或服务端接口,全部经 host 回调交给 api-secret-store:
* 两边共用同一份内存/镜像与「当前账号」,又不会互相 import 成环。
* 只服务桌面客户端(由 host.isDesktopStorage 判定);网页形态不参与。
*/
import { migrateMyApiSecrets, type UserApiSecretItem } from '../api/types/modules/user-secret.ts'
import { withTimeout } from './promise-timeout.ts'
export type SecretProxyMode = 1 | 2
@@ -17,8 +26,19 @@ export interface ApiSecretInheritanceNotice {
proxy: boolean
}
/** 待确认的继承快照摘要:设置页据此弹确认框,确认前不写服务端。 */
export interface PendingApiSecretInheritance {
fromUid: string
fromUsername: string
savedAt: number
moduleKeys: string[]
proxy: boolean
}
export interface ApiSecretInheritanceHost {
currentUid(): string
/** 登出/切号/清缓存都会 +1;与 uid 一起作为「响应是否还属于当前会话」的判据。 */
currentEpoch(): number
isDesktopStorage(): boolean
/** 参与继承的模块 key(服务端必填清单 + 默认清单)。 */
moduleKeys(): Set<string>
@@ -35,107 +55,191 @@ export interface ApiSecretInheritanceHost {
export interface InheritanceOutcome {
count: number
notice: ApiSecretInheritanceNotice | null
/** 快照是否已被消费/清掉;false 表示会话已变或失败,调用方应保留 pending 以便重试。 */
cleared: boolean
}
type InheritedSecretStash = {
schema: 1
export type InheritedSecretStash = {
schema: 2
fromUid: string
fromUsername: string
savedAt: number
osUserScope: string
secrets: Record<string, string>
proxyUrl: string
proxyMode: SecretProxyMode
}
export type InheritanceStashRead =
| { state: 'none' }
| { state: 'invalid' }
| { state: 'valid'; stash: InheritedSecretStash }
const INHERIT_STASH_KEY = 'api_secret_inherit'
/** 作用域标记住在同一个 app.json 里;app.json 本身按 OS 用户分目录,标记用于拒绝跨文件搬来的快照。 */
const OS_SCOPE_KEY = 'api_secret_os_scope'
const INHERIT_SCHEMA = 2
/** 继承快照的有效期:太久以前的登出记录不再往新账号上写(避免半年前的密钥复活)。 */
const INHERIT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
/** 原生桥单次调用预算:登出不能被一个卡死的 read_config/save_config 拖住。 */
const BRIDGE_TIMEOUT_MS = 1000
function readInheritedSecretStash(
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null
}
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function newOsScope(): string {
const cryptoBox = typeof globalThis !== 'undefined'
? (globalThis as { crypto?: { randomUUID?: () => string } }).crypto
: undefined
if (cryptoBox?.randomUUID) return cryptoBox.randomUUID()
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
/** 当前 app.json 的作用域标记;缺失时由 capture 首次写入。 */
export function readOsUserScope(config: Record<string, unknown> | null | undefined): string {
return text(config?.[OS_SCOPE_KEY])
}
function sessionCurrent(host: ApiSecretInheritanceHost, uid: string, epoch: number): boolean {
return host.currentUid() === uid && host.currentEpoch() === epoch
}
/**
* 解析继承快照。结构不符、过期、作用域不一致一律返回 invalid:
* 调用方必须立即把 `api_secret_inherit` 清掉,不能让明文继续留在 app.json。
*/
export function readInheritedSecretStash(
config: Record<string, unknown> | null | undefined,
allowed: Set<string>,
): InheritedSecretStash | null {
): InheritanceStashRead {
const raw = config?.[INHERIT_STASH_KEY]
if (!raw || typeof raw !== 'object') return null
const record = raw as Record<string, unknown>
if (record.schema !== 1) return null
const fromUid = typeof record.fromUid === 'string' ? record.fromUid.trim() : ''
if (raw == null) return { state: 'none' }
const record = asRecord(raw)
if (!record) return { state: 'invalid' }
if (record.schema !== INHERIT_SCHEMA) return { state: 'invalid' }
const fromUid = text(record.fromUid)
const savedAt = typeof record.savedAt === 'number' ? record.savedAt : 0
if (!fromUid || !savedAt || Date.now() - savedAt > INHERIT_MAX_AGE_MS) return null
const osUserScope = text(record.osUserScope)
const currentScope = readOsUserScope(config)
if (!fromUid || !savedAt || !osUserScope || !currentScope) return { state: 'invalid' }
// 同一份 app.json 内 scope 必须对得上;未来时间戳同样视为结构异常
if (osUserScope !== currentScope) return { state: 'invalid' }
if (savedAt > Date.now() + 5 * 60 * 1000) return { state: 'invalid' }
if (Date.now() - savedAt > INHERIT_MAX_AGE_MS) return { state: 'invalid' }
const secretRecord = asRecord(record.secrets)
if (!secretRecord) return { state: 'invalid' }
const proxyRaw = record.proxyUrl
if (proxyRaw != null && typeof proxyRaw !== 'string') return { state: 'invalid' }
const secrets: Record<string, string> = {}
if (record.secrets && typeof record.secrets === 'object') {
for (const [moduleKey, value] of Object.entries(record.secrets as Record<string, unknown>)) {
if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) {
secrets[moduleKey] = value.trim()
}
for (const [moduleKey, value] of Object.entries(secretRecord)) {
if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) {
secrets[moduleKey] = value.trim()
}
}
const proxyUrl = text(proxyRaw)
if (!Object.keys(secrets).length && !proxyUrl) return { state: 'invalid' }
return {
schema: 1,
fromUid,
fromUsername: typeof record.fromUsername === 'string' ? record.fromUsername.trim() : '',
savedAt,
secrets,
proxyUrl: typeof record.proxyUrl === 'string' ? record.proxyUrl.trim() : '',
proxyMode: Number(record.proxyMode) === 2 ? 2 : 1,
state: 'valid',
stash: {
schema: 2,
fromUid,
fromUsername: text(record.fromUsername),
savedAt,
osUserScope,
secrets,
proxyUrl,
proxyMode: Number(record.proxyMode) === 2 ? 2 : 1,
},
}
}
/** 设置页确认框用的摘要(不含明文)。 */
export function toPendingInheritance(stash: InheritedSecretStash): PendingApiSecretInheritance {
return {
fromUid: stash.fromUid,
fromUsername: stash.fromUsername,
savedAt: stash.savedAt,
moduleKeys: Object.keys(stash.secrets),
proxy: Boolean(stash.proxyUrl),
}
}
/**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号**确认后**继承。
* 调用方必须在本页内存/本地镜像被清掉、且 uid 被移除之前调用。
*/
export async function captureSecretsForInheritance(host: ApiSecretInheritanceHost): Promise<void> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return
const uid = host.currentUid()
if (uid === '0') return
const epoch = host.currentEpoch()
const secrets: Record<string, string> = {}
for (const moduleKey of host.moduleKeys()) {
const value = host.readSecret(moduleKey).trim()
if (value) secrets[moduleKey] = value
}
const config = await host.readConfig().catch((error) => {
console.warn('[api-secret] 登出时读取本机代理失败,继承快照将不含代理:', error)
const config = await withTimeout(host.readConfig(), BRIDGE_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 登出时读取本机配置失败,继承快照将不含代理:', error)
return null
})
// 等配置期间可能已经被登出清理:旧账号的快照不能盖到新账号的作用域上
if (!sessionCurrent(host, uid, epoch)) return
const proxy = host.readLocalProxy(config, uid)
const osUserScope = readOsUserScope(config) || newOsScope()
const stash: InheritedSecretStash | null = Object.keys(secrets).length || proxy.url
? {
schema: 1,
schema: 2,
fromUid: uid,
fromUsername: window.localStorage.getItem('username') || '',
savedAt: Date.now(),
osUserScope,
secrets,
proxyUrl: proxy.url,
proxyMode: proxy.mode,
}
: null
await host.saveConfig({ [INHERIT_STASH_KEY]: stash }).catch((error) => {
console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error)
await withTimeout(host.saveConfig({ [OS_SCOPE_KEY]: osUserScope, [INHERIT_STASH_KEY]: stash }), BRIDGE_TIMEOUT_MS)
.catch((error) => {
console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error)
})
}
/** 立即清掉 app.json 里的继承快照(无效快照、用户拒绝、已消费三条路径共用)。 */
export async function clearInheritedSecrets(host: ApiSecretInheritanceHost): Promise<void> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return
await withTimeout(host.saveConfig({ [INHERIT_STASH_KEY]: null }), BRIDGE_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 清理本机继承快照失败:', error)
})
}
/**
* 本机上一个账号留下的配置:只补当前账号服务端空缺的模块,已有值一律不覆盖
* 应用已确认的继承快照:只补当前账号服务端空缺的模块,已有值一律不覆盖
* (服务端 migrate 接口本身也是 fill-only,后台锁定的代理不会被顶掉)。
* 检测状态不继承:那不是配置,不能跨账号冒充已通过。
*
* 每个 await 之后都同时比 uid 与 epoch:确认框打开期间用户可能已经切号/登出,
* 晚到的 migrate 响应或写回都不能落到新账号。
*/
export async function inheritSecretsFromDevice(
export async function applyInheritedSecrets(
host: ApiSecretInheritanceHost,
stash: InheritedSecretStash,
config: Record<string, unknown> | null | undefined,
serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<InheritanceOutcome> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return { count: 0, notice: null }
if (typeof window === 'undefined' || !host.isDesktopStorage()) {
return { count: 0, notice: null, cleared: false }
}
const uid = host.currentUid()
if (uid === '0') return { count: 0, notice: null }
const config = await host.readConfig().catch((error) => {
console.warn('[api-secret] 读取本机继承快照失败(下次加载重试):', error)
return null
})
// 等配置期间可能已经登出/换号:旧账号的快照不能写进新账号的服务端
if (host.currentUid() !== uid) return { count: 0, notice: null }
const stash = readInheritedSecretStash(config, host.moduleKeys())
if (!stash || stash.fromUid === uid) return { count: 0, notice: null }
if (uid === '0') return { count: 0, notice: null, cleared: false }
const epoch = host.currentEpoch()
const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey))
const pending: Array<{ moduleKey: string; value: string }> = []
for (const [moduleKey, value] of Object.entries(stash.secrets)) {
@@ -143,22 +247,26 @@ export async function inheritSecretsFromDevice(
}
// 本机已有代理时以本机为准:它会被代理补报逻辑上报给当前账号,
// 这里再塞上一个账号的代理会让「服务端查商标」和「客户端跑任务」走两条不同的出口。
// 服务端已存在/后台已锁定的代理同样不继承(CR-12:locked 代理必须排除)。
const ownProxy = host.readLocalProxy(config, uid).url
const inheritProxy = Boolean(stash.proxyUrl)
&& Boolean(config)
&& !serverProxyItem?.exists
&& !host.readLocalProxy(config, uid).url
&& !serverProxyItem?.locked
&& !ownProxy
if (inheritProxy) pending.push({ moduleKey: 'proxy', value: stash.proxyUrl })
if (!pending.length) {
await host.saveConfig({ [INHERIT_STASH_KEY]: null }).catch((error) => {
console.warn('[api-secret] 清理已无用的继承快照失败:', error)
})
return { count: 0, notice: null }
await clearInheritedSecrets(host)
return { count: 0, notice: null, cleared: true }
}
const result = await migrateMyApiSecrets(pending).catch((error) => {
console.warn('[api-secret] 继承本机账号密钥失败(下次加载重试):', error)
console.warn('[api-secret] 继承本机账号密钥失败(下次确认时重试):', error)
return null
})
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
const migrated = Number(result?.migrated || 0)
if (!result || migrated <= 0) return { count: 0, notice: null }
if (!result || migrated <= 0) return { count: 0, notice: null, cleared: false }
// migrate 的 await 结束后已经重新比过 uid/epoch,这里才允许把明文写回当前会话的本地镜像
for (const item of pending) {
if (item.moduleKey !== 'proxy') host.writeSecret(item.moduleKey, item.value)
}
@@ -169,12 +277,13 @@ export async function inheritSecretsFromDevice(
await host.saveConfig(patch).catch((error) => {
console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error)
})
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
const notice: ApiSecretInheritanceNotice = {
fromUid: stash.fromUid,
fromUsername: stash.fromUsername,
moduleKeys: pending.filter((item) => item.moduleKey !== 'proxy').map((item) => item.moduleKey),
proxy: inheritProxy,
}
console.log(`[api-secret] 已继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`)
return { count: migrated, notice }
console.log(`[api-secret] 已确认继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`)
return { count: migrated, notice, cleared: true }
}
+283 -56
View File
@@ -23,15 +23,24 @@ import {
type UserApiSecretItem,
} from '../api/types/modules/user-secret.ts'
import {
applyInheritedSecrets,
captureSecretsForInheritance,
inheritSecretsFromDevice,
clearInheritedSecrets,
readInheritedSecretStash,
toPendingInheritance,
type ApiSecretInheritanceHost,
type ApiSecretInheritanceNotice,
type InheritedSecretStash,
type PendingApiSecretInheritance,
} from './api-secret-inheritance.ts'
import { withTimeout } from './promise-timeout.ts'
import type { DesktopConfigUpdate } from '../bridges/pywebview.ts'
export type { ApiSecretModuleKey, ApiSecretCheckStatus }
export type { ApiSecretInheritanceNotice } from './api-secret-inheritance.ts'
export type {
ApiSecretInheritanceNotice,
PendingApiSecretInheritance,
} from './api-secret-inheritance.ts'
export type { UserApiSecretCheckResult }
@@ -79,6 +88,10 @@ const LEGACY_MODULE_KEYS = ['appearance-patent', 'appearance-patent-token', 'sim
const MIGRATED_FLAG_PREFIX = 'brand:api-secret-migrated'
const DEFAULT_REQUIRED_MODULES: ApiSecretModuleKey[] = ['appearance-patent', 'similar-asin']
const FETCH_TIMEOUT_MS = 4000
/** 登出继承快照的整体预算:原生桥卡死也必须让登出清理继续走。 */
const CAPTURE_TIMEOUT_MS = 2500
/** 读/写 app.json 的单次预算:doLoad 不能被一个永不返回的桥调用挂住。 */
const CONFIG_TIMEOUT_MS = 3000
const memory = new Map<string, ApiSecretCacheEntry>()
const listeners = new Set<() => void>()
@@ -101,6 +114,14 @@ let inflightLoad: Promise<ApiSecretLoadState> | null = null
let serverProxy: ServerProxySnapshot | null = null
/** 本次登录继承到的配置摘要:设置页消费一次,不落盘(避免多一个明文旁路)。 */
let inheritanceNotice: ApiSecretInheritanceNotice | null = null
/**
* 本机上一个账号留下、等待用户显式确认的继承快照(CR-12)。
* 确认前不写服务端、不写本地镜像;登出/切号时连同摘要一起作废。
*/
let pendingInheritance: {
summary: PendingApiSecretInheritance
stash: InheritedSecretStash
} | null = null
/** 登出/切号会让在飞的密钥加载失效,防止 A 的响应落到 B 的会话里。 */
let cacheEpoch = 0
/** 上一次读到的登录 uid:会话过期后直接换号登录时,内存里的旧账号明文必须就地作废。 */
@@ -115,12 +136,18 @@ function currentUid(): string {
inflightLoad = null
serverProxy = null
inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1
}
cachedUid = uid
return uid
}
/** 响应回写前的统一闸门:uid 与 epoch 必须同时还是发起请求时那一个。 */
function sessionCurrent(uid: string, epoch: number): boolean {
return currentUid() === uid && cacheEpoch === epoch
}
function buildMirrorKey(moduleKey: string) {
return `${MIRROR_PREFIX}:${currentUid()}:${moduleKey}`
}
@@ -412,8 +439,12 @@ export function ensureApiSecretsLoaded(): Promise<ApiSecretLoadState> {
async function applyServerBundle(
bundle: UserApiSecretBundle | null | undefined,
uid: string,
epoch: number,
): Promise<void> {
// 先用调用方发请求时的 uid/epoch 验身,再动内存/镜像:
// 不能在这里重新 currentUid()——那会把「已经换成 B」当成合法会话,把 A 的包写进 B。
if (!sessionCurrent(uid, epoch)) return
if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) {
requiredModules = bundle.requiredModules
}
@@ -424,54 +455,50 @@ async function applyServerBundle(
}
serverProxy = toServerProxy(bundle?.proxy)
// 登出/换号可能发生在读配置的等待里:旧账号的锁定代理绝不能写进新账号的本地配置
if (epoch !== cacheEpoch) return
if (!sessionCurrent(uid, epoch)) return
if (serverProxy?.locked && serverProxy.full) {
// 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默
await syncLockedProxyToLocal(serverProxy.full)
await syncLockedProxyToLocal(serverProxy.full, uid, epoch)
// write 之前再比一次:sync 内部的 await 期间可能已经切号/登出
if (!sessionCurrent(uid, epoch)) return
}
}
async function doLoad(): Promise<ApiSecretLoadState> {
// 换号(含会话过期后直接登录 B)时先作废旧账号缓存,再取 epoch:
// 反序会把本次加载自己判成“过期响应”,继承与门禁都走不到。
currentUid()
const uid = currentUid()
const epoch = cacheEpoch
try {
let bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
bundleLoaded = true
notify()
const migrated = await tryMigrateLocalSecrets(bundle?.items || [])
if (epoch !== cacheEpoch) return 'unknown'
const migrated = await tryMigrateLocalSecrets(bundle?.items || [], uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
if (migrated > 0) {
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
notify()
}
// 继承必须排在旧本地密钥迁移之后:两者都走 fill-only,谁先占住服务端空缺谁生效,
// 而当前账号自己的旧记录理应优先于上一个账号留下的快照。
// CR-12:这里只登记待确认快照,不再自动 migrate——明文是否跨账号复用必须由用户拍板。
if (bundle && Array.isArray(bundle.items)) {
const inherited = await tryInheritSecretsFromDevice(bundle.items, bundle.proxy)
if (epoch !== cacheEpoch) return 'unknown'
if (inherited > 0) {
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
notify()
}
await stageInheritance(bundle.items, bundle.proxy, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
}
const backfilled = await tryBackfillProxyToServer()
if (epoch !== cacheEpoch) return 'unknown'
const backfilled = await tryBackfillProxyToServer(uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
if (backfilled) {
// 补报已写入服务端:重拉一次让 serverProxy 反映新状态,
// 否则任务提交前的代理检查会拿到上一轮的空快照。
const refreshed = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
serverProxy = toServerProxy(refreshed?.proxy)
notify()
}
@@ -483,7 +510,11 @@ async function doLoad(): Promise<ApiSecretLoadState> {
}
/** 旧本地密钥一次性迁移:仅当服务端空缺且有本地明文时上报;失败静默,下次加载重试。 */
async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise<number> {
async function tryMigrateLocalSecrets(
serverItems: UserApiSecretItem[],
uid: string,
epoch: number,
): Promise<number> {
if (typeof window === 'undefined') return 0
try {
if (window.localStorage.getItem(migratedFlagKey()) === '1') {
@@ -505,6 +536,8 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
return 0
}
const result = await migrateMyApiSecrets(pending)
// 等接口期间可能已登出/切号:旧账号的明文不能再写进当前账号的本地镜像
if (!sessionCurrent(uid, epoch)) return 0
const migrated = Number(result?.migrated || 0)
// 迁移成功后本地保留明文(供提交任务直接使用),只清理旧记录与标记
for (const item of pending) {
@@ -527,17 +560,25 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
*
* @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。
*/
async function tryBackfillProxyToServer(): Promise<boolean> {
async function tryBackfillProxyToServer(uid: string, epoch: number): Promise<boolean> {
try {
const uid = currentUid()
if (uid === '0') return false
const config = await readConfigForBackfill()
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 读取本机代理配置失败(下次加载重试):', error)
return null
})
if (!config) return false
// 等配置期间可能已经登出/换号:补报请求会带新账号令牌,必须放弃旧账号的本地代理
if (currentUid() !== uid) return false
const url = readLocalProxyUrl(config)
if (!sessionCurrent(uid, epoch)) return false
// 升级一次性归属迁移:老版本只存全局 proxy_url、没有 proxy_uid。
// 第一个读到它的账号把它认领成自己的(写入 proxy_users[uid] + proxy_uid 并清空全局),
// 之后其他账号再登录就不会静默回退到这个代理(CR-04)。
const ownedConfig = await claimLegacyGlobalProxy(config, uid)
if (!sessionCurrent(uid, epoch)) return false
const url = readLocalProxyUrl(ownedConfig, uid)
if (!url) return false
const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }])
if (!sessionCurrent(uid, epoch)) return false
return Number(result?.migrated || 0) > 0
} catch (error) {
console.warn('[api-secret] 代理配置补报失败(下次加载重试):', error)
@@ -564,17 +605,96 @@ async function readConfigForBackfill(): Promise<Record<string, unknown> | null>
return (await api.read_config()) as Record<string, unknown> | null
}
/** 写回本机配置:与 readConfigForBackfill 同一套桥选择;写成功返回 true。 */
async function saveConfigForBackfill(patch: Record<string, unknown>): Promise<boolean> {
if (typeof window === 'undefined') return false
const direct = window.pywebview?.api
if (direct?.save_config) {
await direct.save_config(patch as DesktopConfigUpdate)
return true
}
if (typeof document === 'undefined') return false
const { getPywebviewApi } = await import('../bridges/pywebview.ts')
const api = getPywebviewApi()
if (!api?.save_config) return false
await api.save_config(patch as DesktopConfigUpdate)
return true
}
/**
* 读取当前登录用户的本地代理地址:proxy_users[uid] 优先,用户项为空时回退全局 proxy_url。
* 回退口径与客户端任务链 `resolve_current_proxy` 一致——老版本把代理存在全局 proxy_url,
* 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在
* 商标维度整批判失败(2026-10-25 账号 1210 的 32300/32309 就是这么来的)。
* 无归属的全局 proxy_url 一次性归给当前 uid(CR-04)。
*
* 老版本把代理存在全局 proxy_url(2026-10-25 账号 1210 的 32300/32309 就靠这条路径补报),
* 但全局字段本身不带归属,A 留下的代理会被 B 静默继承。升级时由第一个读到它的账号认领:
* 写入 `proxy_users[uid]` 与 `proxy_uid`,随后清空全局 `proxy_url`。
* 认领失败(桥没有 save_config 或写入抛错)时不回退——宁可不补报,也不把出口写给别的账号。
*/
async function claimLegacyGlobalProxy(
config: Record<string, unknown> | null | undefined,
uid: string,
): Promise<Record<string, unknown> | null | undefined> {
if (!config || uid === '0') return config
const globalUrl = typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
// 归属 0 等同未登录时的匿名全局,按"无归属"处理;只有明确归属到别的 uid 才绝不碰
if (!globalUrl || (owner && owner !== '0')) return config
const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = users[uid]
const ownRecord = own && typeof own === 'object' && !Array.isArray(own)
? own as Record<string, unknown>
: {}
const ownUrl = typeof ownRecord.proxy_url === 'string' ? ownRecord.proxy_url.trim() : ''
if (ownUrl && !isSharedProxy(config, uid)) {
// 当前账号已有自己的代理:全局字段是历史残留,归给当前 uid 后清空,
// 避免下一个账号把它当成"无主代理"认领走。
// 若全局是显式共享(proxy_shared/proxy_shared_uids)则保留给其他账号。
const cleared = await saveConfigForBackfill({ proxy_url: '', proxy_uid: uid }).catch((error) => {
console.warn('[api-secret] 清理本机残留全局代理失败(下次加载重试):', error)
return false
})
return cleared ? { ...config, proxy_url: '', proxy_uid: uid } : config
}
const mode = Number(config.proxy_mode) === 2 ? 2 : 1
const saved = await saveConfigForBackfill({
proxy_url: '',
proxy_uid: uid,
proxy_users: { [uid]: { ...ownRecord, proxy_url: globalUrl, proxy_mode: mode } },
}).catch((error) => {
console.warn('[api-secret] 全局代理归属迁移失败(不静默回退给当前账号):', error)
return false
})
if (!saved) return config
return {
...config,
proxy_url: '',
proxy_uid: uid,
proxy_users: { ...users, [uid]: { ...ownRecord, proxy_url: globalUrl, proxy_mode: mode } },
}
}
/** 显式共享白名单:`proxy_shared=true`(整机共享)或 `proxy_shared_uids` 包含当前 uid。 */
function isSharedProxy(config: Record<string, unknown> | null | undefined, uid: string): boolean {
if (!config) return false
if (config.proxy_shared === true) return true
return Array.isArray(config.proxy_shared_uids)
&& config.proxy_shared_uids.some((item) => String(item).trim() === uid)
}
/**
* 读取当前登录用户的本地代理地址。
*
* 回退顺序(CR-04):proxy_users[uid] → 全局 proxy_url **且归属就是当前 uid**
* (或显式共享白名单 `proxy_shared=true` / `proxy_shared_uids` 包含当前 uid)。
* 全局字段未归属/归属别人时返回空,绝不再把上一个账号的出口补报给当前账号。
* 未登录(uid=0)只认匿名全局或共享白名单,不碰实名归属的代理。
*/
function readLocalProxyEntry(
config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): { url: string; mode: 1 | 2 } {
if (!config) return { url: '', mode: 1 }
const globalUrl = typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
const globalMode: 1 | 2 = Number(config.proxy_mode) === 2 ? 2 : 1
if (uid !== '0') {
const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) as Record<string, unknown>
@@ -583,14 +703,25 @@ function readLocalProxyEntry(
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
}
}
return {
url: typeof config.proxy_url === 'string' ? config.proxy_url.trim() : '',
mode: Number(config.proxy_mode) === 2 ? 2 : 1,
const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
const shared = isSharedProxy(config, uid)
if (!globalUrl) return { url: '', mode: 1 }
if (uid === '0') {
// 未登录没有"账号归属"可言:只认匿名全局(无归属/归属 0)或显式共享
return !owner || owner === '0' || shared
? { url: globalUrl, mode: globalMode }
: { url: '', mode: 1 }
}
return owner === uid || shared
? { url: globalUrl, mode: globalMode }
: { url: '', mode: 1 }
}
function readLocalProxyUrl(config: Record<string, unknown> | null | undefined): string {
return readLocalProxyEntry(config).url
function readLocalProxyUrl(
config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): string {
return readLocalProxyEntry(config, uid).url
}
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
@@ -615,15 +746,18 @@ function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxy
* 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。
* 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。
*/
async function syncLockedProxyToLocal(full: string): Promise<void> {
async function syncLockedProxyToLocal(
full: string,
uidAtStart: string,
epochAtStart: number,
): Promise<void> {
try {
if (typeof window === 'undefined') return
const api = window.pywebview?.api
if (!api?.read_config || !api?.save_config) return
const uidAtStart = currentUid()
const config = (await api.read_config()) as Record<string, unknown> | null
if (currentUid() !== uidAtStart) return
if (readLocalProxyUrl(config) === full) return
if (!sessionCurrent(uidAtStart, epochAtStart)) return
if (readLocalProxyUrl(config, uidAtStart) === full) return
const uid = uidAtStart
if (uid === '0') {
const mode = Number(config?.proxy_mode) === 2 ? 2 : 1
@@ -635,6 +769,8 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
// 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 } } })
// save 的 await 之后不再有写操作;保留一次检查让"迟到响应不落到新账号"的口径可被测试钉住
if (!sessionCurrent(uidAtStart, epochAtStart)) return
} catch (error) {
console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error)
}
@@ -642,40 +778,130 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
const inheritanceHost: ApiSecretInheritanceHost = {
currentUid,
currentEpoch: () => cacheEpoch,
isDesktopStorage: isNativeDesktopStorage,
moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]),
readSecret: (moduleKey) => readEntry(moduleKey).value,
// 只有 applyInheritedSecrets 在 migrate 的 await 之后重新比过 uid/epoch 才会调到这里
writeSecret: (moduleKey, value) => {
const entry = readEntry(moduleKey)
updateEntry(moduleKey, { value: entry.value || value })
},
readConfig: () => readConfigForBackfill(),
saveConfig: async (patch) => {
const api = window.pywebview?.api
if (!api?.save_config) return
await Promise.resolve(api.save_config(patch as DesktopConfigUpdate))
},
saveConfig: (patch) => saveConfigForBackfill(patch),
readLocalProxy: readLocalProxyEntry,
}
/**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号**确认后**继承。
*
* 只走桌面真实桥(网页形态没有本地任务链,也不该把明文留给浏览器);
* 必须在本页内存/本地镜像被 clearApiSecretCache 清掉、且 localStorage.uid 被移除之前调用,
* 否则读到的会是空值或另一个 uid 的镜像。
*
* 外层再加一道整体超时:桥卡死时调用方(登录页)必须能继续清 token/uid,
* 不能让登出停在"还在清"的状态里(CR-12)。
*/
export function captureApiSecretsForInheritance(): Promise<void> {
return captureSecretsForInheritance(inheritanceHost)
return withTimeout(captureSecretsForInheritance(inheritanceHost), CAPTURE_TIMEOUT_MS)
}
async function tryInheritSecretsFromDevice(
/**
* 读取本机继承快照并登记为待确认(CR-12:不再自动 migrate)。
* 无效/过期/作用域不符的快照在这里立即清掉,避免明文密钥无限期留在 app.json。
*/
async function stageInheritance(
serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<number> {
const outcome = await inheritSecretsFromDevice(inheritanceHost, serverItems, serverProxyItem)
if (outcome.notice) inheritanceNotice = outcome.notice
return outcome.count
uid: string,
epoch: number,
): Promise<void> {
if (!isNativeDesktopStorage()) {
pendingInheritance = null
return
}
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 读取本机继承快照失败(下次加载重试):', error)
return null
})
if (!sessionCurrent(uid, epoch)) return
const parsed = readInheritedSecretStash(config, inheritanceHost.moduleKeys())
if (parsed.state === 'none') {
pendingInheritance = null
return
}
if (parsed.state === 'invalid' || parsed.stash.fromUid === uid) {
await clearInheritedSecrets(inheritanceHost)
if (sessionCurrent(uid, epoch)) pendingInheritance = null
return
}
const stash = parsed.stash
const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey))
const secretNeeded = Object.keys(stash.secrets).some((moduleKey) => !serverHas.has(moduleKey))
const proxyNeeded = Boolean(stash.proxyUrl) && !serverProxyItem?.exists && !serverProxyItem?.locked
if (!secretNeeded && !proxyNeeded) {
// 服务端已经没有可补的项:快照没有存在价值,立即清掉
await clearInheritedSecrets(inheritanceHost)
if (sessionCurrent(uid, epoch)) pendingInheritance = null
return
}
if (!sessionCurrent(uid, epoch)) return
pendingInheritance = { summary: toPendingInheritance(stash), stash }
}
/** 设置页读取待确认的继承摘要(不含明文)。确认前不会写服务端。 */
export function getPendingApiSecretInheritance(): PendingApiSecretInheritance | null {
return pendingInheritance?.summary || null
}
/**
* 用户点「继承」后执行迁移:只补服务端空缺项,服务端已锁定/已存在的代理不继承。
* 成功返回本次继承摘要;网络失败或会话已变时保留 pending 供下次重试。
*/
export async function confirmApiSecretInheritance(): Promise<ApiSecretInheritanceNotice | null> {
const pending = pendingInheritance
if (!pending || !isNativeDesktopStorage()) return null
const uid = currentUid()
const epoch = cacheEpoch
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 确认继承时读取本机配置失败(保留快照待重试):', error)
return null
})
if (!config || !sessionCurrent(uid, epoch)) return null
const bundle = await fetchMyApiSecrets().catch((error) => {
console.warn('[api-secret] 确认继承时拉取服务端密钥失败(保留快照待重试):', error)
return null
})
if (!bundle || !sessionCurrent(uid, epoch)) return null
const outcome = await applyInheritedSecrets(
inheritanceHost,
pending.stash,
config,
bundle.items || [],
bundle.proxy,
)
if (!sessionCurrent(uid, epoch)) return null
if (outcome.cleared) pendingInheritance = null
if (!outcome.notice) return null
inheritanceNotice = outcome.notice
const refreshed = await fetchMyApiSecrets().catch((error) => {
console.warn('[api-secret] 继承后刷新服务端密钥失败(下次加载会重试):', error)
return null
})
if (refreshed && sessionCurrent(uid, epoch)) {
await applyServerBundle(refreshed, uid, epoch)
if (sessionCurrent(uid, epoch)) {
bundleLoaded = true
notify()
}
}
return outcome.notice
}
/** 用户点「不继承」:立即清掉本机快照,明文不再留在 app.json。 */
export async function declineApiSecretInheritance(): Promise<void> {
pendingInheritance = null
await clearInheritedSecrets(inheritanceHost)
}
/** 设置页消费一次继承提示(内存态,不落盘)。 */
@@ -739,6 +965,7 @@ export function clearApiSecretCache(): void {
inflightLoad = null
serverProxy = null
inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1
}
@@ -0,0 +1,33 @@
/**
* 给桌面桥调用加一道硬超时。
*
* 登出时要把本账号配置留给本机下一个账号,但原生桥(read_config/save_config)在
* 主进程卡死或 pywebview 未就绪时可能永不返回。没有超时,登出清理会一直等,
* 令牌与 uid 留在 localStorage 里,用户还能在原页面继续操作(CR-12)。
*
* 超时只负责让调用方继续走清理,不取消底层 promise:桥调用本身没有取消接口,
* 晚到的结果最多是写了一份已经过期的继承快照,不会回写登录态。
*/
export class PromiseTimeoutError extends Error {
constructor(timeoutMs: number) {
super(`操作超过 ${timeoutMs}ms 未完成`)
this.name = 'PromiseTimeoutError'
}
}
export function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
if (!(timeoutMs > 0)) return promise
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new PromiseTimeoutError(timeoutMs)), timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
},
)
})
}
@@ -155,6 +155,22 @@ test('登出先留继承快照再清缓存,且清缓存必须早于移除 uid'
)
})
test('登出清理期间禁用提交,且清理结束才恢复(CR-12)', () => {
assert.match(loginPageSource, /logoutCleanupPending = ref\(false\)/, '缺清理中状态')
assert.match(
loginPageSource,
/:disabled="loggingIn \|\| logoutCleanupPending"/,
'清理期间登录按钮必须禁用',
)
assert.match(
loginPageSource,
/if \(loggingIn\.value \|\| logoutCleanupPending\.value\) return/,
'回车/表单提交也要挡住,不能只靠按钮 disabled',
)
assert.match(loginPageSource, /logoutCleanupPending\.value = true/, '登出时应进入清理中状态')
assert.match(loginPageSource, /logoutCleanupPending\.value = false/, '清理结束(含超时)必须恢复')
})
test('停用/删除文案必须互不冒充:停用句不说删除、删除句不说停用', () => {
const disabledLine = loginPageSource
.split('\n')
@@ -0,0 +1,31 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { PromiseTimeoutError, withTimeout } from '../src/shared/utils/promise-timeout.ts'
/**
* 登出 capture 的超时底座(CR-12):原生桥卡死时必须让调用方继续清 token/uid。
* 这里只验超时原语本身;capture 走超时后仍写快照/继续清理的分支在 secret-store.test.ts。
*/
test('withTimeout 在期限内原样返回结果', async () => {
await assert.doesNotReject(async () => {
const value = await withTimeout(Promise.resolve('ok'), 50)
assert.equal(value, 'ok')
})
})
test('withTimeout 对永不返回的 promise 按时抛 PromiseTimeoutError', async () => {
const start = Date.now()
await assert.rejects(
() => withTimeout(new Promise(() => {}), 20),
(error: unknown) => error instanceof PromiseTimeoutError && /超过 20ms 未完成/.test(error.message),
)
assert.ok(Date.now() - start < 1000, '超时必须及时触发,不能等底层 promise')
})
test('withTimeout 透传底层拒绝(吞掉会伪造成功)', async () => {
await assert.rejects(
() => withTimeout(Promise.reject(new Error('bridge down')), 50),
/bridge down/,
)
})
+345 -8
View File
@@ -4,7 +4,10 @@ import { http } from '../src/shared/api/http.ts'
import {
captureApiSecretsForInheritance,
clearApiSecretCache,
confirmApiSecretInheritance,
declineApiSecretInheritance,
ensureBrandCheckProxy,
getPendingApiSecretInheritance,
getServerProxySnapshot,
getStoredApiSecret,
getStoredApiSecretSnapshot,
@@ -199,9 +202,18 @@ test('test_secret_store_backfills_legacy_global_proxy_to_server', async (t) => {
clearApiSecretCache()
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=legacy'
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
const saveCalls: Array<Record<string, unknown>> = []
let config: Record<string, unknown> = { proxy_url: globalUrl, proxy_mode: 2 }
let bundleCalls = 0
// 老版本只把代理存在全局 proxy_url,proxy_users 里没有该用户
attachDesktopBridge(() => ({ proxy_url: globalUrl, proxy_mode: 2 }), (patch) => patch)
attachDesktopBridge(
() => config,
(patch) => {
saveCalls.push(patch)
config = mergeDesktopConfig(config, patch)
return config
},
)
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
@@ -226,6 +238,15 @@ test('test_secret_store_backfills_legacy_global_proxy_to_server', async (t) => {
.find((item) => item.moduleKey === 'proxy')
assert.equal(proxyMigrate?.value, globalUrl, '旧版全局代理应补报到服务端')
assert.equal(getServerProxySnapshot()?.exists, true, '补报后应重拉服务端代理快照')
// CR-04:升级时一次性归属迁移——全局 proxy 归给第一个读到它的 uid,并清空全局
assert.equal(config.proxy_uid, '42', '全局代理应被当前 uid 认领')
assert.equal(config.proxy_url, '', '认领后应清空无归属的全局 proxy_url')
assert.equal(
(config.proxy_users as Record<string, { proxy_url: string }>)['42'].proxy_url,
globalUrl,
'认领结果应写入 proxy_users[uid]',
)
assert.ok(saveCalls.some((patch) => patch.proxy_uid === '42'), '归属迁移必须落盘,不能只在内存里认领')
})
test('test_secret_store_user_proxy_wins_over_legacy_global', async (t) => {
@@ -315,6 +336,45 @@ function mergeDesktopConfig(current: Record<string, unknown>, patch: Record<stri
return next
}
/** 可变的桌面 app.json:读当前值、写回按原生 save_config 口径合并,并记录每次 patch。 */
function attachConfigStore(initial: Record<string, unknown>) {
let config = initial
const saveCalls: Array<Record<string, unknown>> = []
attachDesktopBridge(
() => config,
(patch) => {
saveCalls.push(patch)
config = mergeDesktopConfig(config, patch)
return config
},
)
return {
get config() {
return config
},
saveCalls,
}
}
/** 合法的本机继承快照(schema 2 + 同作用域),测试按需覆盖字段。 */
function validInheritanceConfig(overrides: Record<string, unknown> = {}) {
return {
current_uid: '43',
api_secret_os_scope: 'scope-1',
api_secret_inherit: {
schema: 2,
fromUid: '42',
fromUsername: 'alice',
savedAt: Date.now(),
osUserScope: 'scope-1',
secrets: { 'appearance-patent': 'sk-alice-appearance' },
proxyUrl: '',
proxyMode: 1,
...overrides,
},
}
}
test('test_secret_store_inherits_previous_account_config_on_desktop', async (t) => {
const { localStorage } = setupWindow()
clearApiSecretCache()
@@ -337,6 +397,8 @@ test('test_secret_store_inherits_previous_account_config_on_desktop', async (t)
await captureApiSecretsForInheritance()
const stash = config.api_secret_inherit as Record<string, unknown> | null
assert.equal(stash?.fromUid, '42', '登出时应把当前账号配置留成本机继承快照')
assert.equal(stash?.schema, 2, '快照必须带当前 schema 与 OS 作用域')
assert.equal(stash?.osUserScope, config.api_secret_os_scope, '快照作用域必须与本机 app.json 一致')
// 真实登出顺序:先清缓存(此时 uid 仍是 42),再移除 uid;登录 B 后 uid=43
clearApiSecretCache()
@@ -370,33 +432,44 @@ test('test_secret_store_inherits_previous_account_config_on_desktop', async (t)
await loadApiSecrets({ force: true })
// CR-12:加载只登记待确认,不再自动继承
assert.deepEqual(migratePayloads, [], '用户未确认前不得调用 migrate')
const pending = getPendingApiSecretInheritance()
assert.equal(pending?.fromUid, '42')
assert.equal(pending?.fromUsername, 'alice')
assert.equal(pending?.proxy, true)
assert.deepEqual(pending?.moduleKeys.slice().sort(), ['appearance-patent', 'similar-asin'])
assert.equal(getStoredApiSecret('appearance-patent'), '', '确认前不得把上一个账号的明文写进本地镜像')
const notice = await confirmApiSecretInheritance()
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
assert.equal(
migrated.find((item) => item.moduleKey === 'appearance-patent')?.value,
'sk-alice-appearance',
'上一个账号的外观专利密钥应继承给当前账号',
'确认后上一个账号的外观专利密钥应继承给当前账号',
)
assert.equal(
migrated.find((item) => item.moduleKey === 'similar-asin')?.value,
'sk-alice-similar',
'上一个账号的货源查询密钥应继承给当前账号',
'确认后上一个账号的货源查询密钥应继承给当前账号',
)
assert.equal(
migrated.find((item) => item.moduleKey === 'proxy')?.value,
aliceProxy,
'服务端缺代理时应继承上一个账号的代理',
'服务端缺代理且未锁定时应继承上一个账号的代理',
)
assert.equal(getStoredApiSecret('appearance-patent'), 'sk-alice-appearance', '继承后当前账号本地应能直接取到明文')
const users = config.proxy_users as Record<string, { proxy_url: string; proxy_mode: number }>
assert.equal(users['43'].proxy_url, aliceProxy, '继承的代理应写进当前 uid 的本地配置')
assert.equal(users['43'].proxy_mode, 2, '代理模式应一并继承')
assert.equal(config.api_secret_inherit, null, '继承成功后快照应消费掉,避免被更后面的账号重复使用')
assert.equal(config.api_secret_inherit, null, '确认继承后快照应消费掉,避免被更后面的账号重复使用')
assert.equal(getPendingApiSecretInheritance(), null, '确认后不应再有待确认摘要')
const notice = takeApiSecretInheritanceNotice()
assert.equal(notice?.fromUid, '42')
assert.equal(notice?.fromUsername, 'alice')
assert.equal(notice?.proxy, true)
assert.deepEqual(notice?.moduleKeys.slice().sort(), ['appearance-patent', 'similar-asin'])
assert.equal(takeApiSecretInheritanceNotice()?.fromUid, '42', '设置页应能消费到本次继承提示')
})
test('test_secret_store_inheritance_never_overwrites_existing_account_config', async (t) => {
@@ -405,11 +478,13 @@ test('test_secret_store_inheritance_never_overwrites_existing_account_config', a
localStorage.setItem('uid', '43')
const config: Record<string, unknown> = {
current_uid: '43',
api_secret_os_scope: 'scope-1',
api_secret_inherit: {
schema: 1,
schema: 2,
fromUid: '42',
fromUsername: 'alice',
savedAt: Date.now(),
osUserScope: 'scope-1',
secrets: { 'appearance-patent': 'sk-alice-appearance', 'similar-asin': 'sk-alice-similar' },
proxyUrl: 'https://api.jikip.com/ip-get?num=1&key=alice',
proxyMode: 2,
@@ -441,6 +516,10 @@ test('test_secret_store_inheritance_never_overwrites_existing_account_config', a
await loadApiSecrets({ force: true })
assert.deepEqual(migratePayloads, [], '用户未确认前不得自动继承')
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42', '应登记待确认快照')
await confirmApiSecretInheritance()
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
assert.deepEqual(
migrated.map((item) => item.moduleKey),
@@ -448,7 +527,7 @@ test('test_secret_store_inheritance_never_overwrites_existing_account_config', a
'只补当前账号空缺的模块,已有密钥和已有代理都不能被上一个账号覆盖',
)
assert.equal(getStoredApiSecret('appearance-patent'), '', '当前账号已有密钥时不得把上一个账号的明文塞进本地')
assert.equal(config.api_secret_inherit, null, '没有需要补的项时也应消费快照')
assert.equal(config.api_secret_inherit, null, '继承完成后应消费快照')
assert.equal(
(config.proxy_users as Record<string, unknown> | undefined)?.['43'],
undefined,
@@ -456,6 +535,264 @@ test('test_secret_store_inheritance_never_overwrites_existing_account_config', a
)
})
test('test_secret_store_declines_inheritance_and_clears_stash', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const store = attachConfigStore(validInheritanceConfig())
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
return okResponse({ migrated: 1 })
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42', '应先登记待确认快照')
await declineApiSecretInheritance()
assert.equal(store.config.api_secret_inherit, null, '用户选择不继承后快照必须立即清掉')
assert.equal(getPendingApiSecretInheritance(), null)
assert.deepEqual(migratePayloads, [], '拒绝继承不得调用 migrate')
})
test('test_secret_store_expired_inheritance_snapshot_is_cleared', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const store = attachConfigStore(validInheritanceConfig({
savedAt: Date.now() - 31 * 24 * 60 * 60 * 1000,
}))
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
return okResponse({ migrated: 1 })
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
assert.equal(store.config.api_secret_inherit, null, '过期快照必须立即从 app.json 清掉(明文不许长期留存)')
assert.equal(getPendingApiSecretInheritance(), null)
assert.deepEqual(migratePayloads, [])
})
test('test_secret_store_malformed_inheritance_snapshot_is_cleared', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const store = attachConfigStore(validInheritanceConfig({ schema: 1 }))
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
await loadApiSecrets({ force: true })
assert.equal(store.config.api_secret_inherit, null, '结构不符(旧 schema/缺作用域)必须立即清掉')
assert.equal(getPendingApiSecretInheritance(), null)
})
test('test_secret_store_inheritance_scope_mismatch_is_cleared', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
// 别的 OS 用户 app.json 里拷来的快照:作用域标记对不上
const store = attachConfigStore(validInheritanceConfig({ osUserScope: 'scope-from-another-os-user' }))
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
await loadApiSecrets({ force: true })
assert.equal(store.config.api_secret_inherit, null, '跨 OS 用户作用域的快照必须清掉')
assert.equal(getPendingApiSecretInheritance(), null)
})
test('test_secret_store_locked_server_proxy_is_not_inherited', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const stashProxy = 'https://api.jikip.com/ip-get?num=1&key=alice'
const store = attachConfigStore(validInheritanceConfig({ proxyUrl: stashProxy, proxyMode: 2 }))
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
const payload = req.data as { items?: Array<{ moduleKey?: string; value?: string }> }
migratePayloads.push(payload)
return okResponse({ migrated: payload.items?.length || 0 })
}
return okResponse({
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
requiredModules: ['appearance-patent', 'similar-asin'],
complete: false,
// 后台锁定但 exists 仍为 false:只靠 exists 判断会漏掉 locked 这一条
proxy: { ...serverItem('proxy'), exists: false, locked: true },
})
})
await loadApiSecrets({ force: true })
const notice = await confirmApiSecretInheritance()
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
assert.equal(
migrated.some((item) => item.moduleKey === 'proxy'),
false,
'后台锁定的代理不得被上一个账号的快照覆盖',
)
assert.equal(notice?.proxy, false, '继承摘要要如实说明代理没有继承')
assert.equal(
(store.config.proxy_users as Record<string, unknown> | undefined)?.['43'],
undefined,
'锁定代理场景不得把快照代理写进本地配置',
)
})
test('test_secret_store_inheritance_write_aborts_when_uid_changes', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const store = attachConfigStore(validInheritanceConfig())
let releaseMigrate: ((value: unknown) => void) | null = null
let markStarted: (() => void) | null = null
const migrateStarted = new Promise<void>((resolve) => {
markStarted = resolve
})
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
markStarted?.()
return new Promise((resolve) => {
releaseMigrate = resolve
})
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42')
const confirmPromise = confirmApiSecretInheritance()
await migrateStarted
// migrate 在飞时切号:晚到的成功响应不得把 A 的明文写进 B 的本地镜像
localStorage.setItem('uid', '44')
releaseMigrate?.({ data: { success: true, message: 'ok', data: { migrated: 1 } } })
const notice = await confirmPromise
assert.equal(notice, null, '会话已变时确认流程必须返回空')
assert.equal(getStoredApiSecret('appearance-patent'), '', '切号后不得写入上一个账号的明文')
assert.equal(
(store.config.proxy_users as Record<string, unknown> | undefined)?.['43'],
undefined,
'切号后不得写回上一个账号的代理',
)
assert.ok(store.config.api_secret_inherit, '会话已变时快照应保留给正确账号重试,而不是被误清')
})
test('test_secret_store_does_not_backfill_foreign_global_proxy', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const aliceProxy = 'https://api.jikip.com/ip-get?num=1&key=alice'
const store = attachConfigStore({
proxy_users: { '43': {} },
proxy_url: aliceProxy,
proxy_uid: '42',
})
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
return okResponse({ migrated: 1 })
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
assert.equal(
migratePayloads.flatMap((payload) => payload.items || []).some((item) => item.moduleKey === 'proxy'),
false,
'全局代理归属 uid=42 时,uid=43 不得静默补报',
)
assert.equal(store.config.proxy_uid, '42', '不得把别人的全局代理改归属到当前账号')
assert.deepEqual(store.config.proxy_users, { '43': {} }, '也不得写进当前 uid 的 proxy_users')
assert.deepEqual(store.saveCalls, [], '归属不符时不应发生任何配置写回')
})
test('test_secret_store_backfills_global_proxy_owned_by_current_uid', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const ownProxy = 'https://api.jikip.com/ip-get?num=1&key=owned'
const store = attachConfigStore({ proxy_url: ownProxy, proxy_uid: '43' })
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
return okResponse({ migrated: 1 })
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
const proxyMigrate = migratePayloads
.flatMap((payload) => payload.items || [])
.find((item) => item.moduleKey === 'proxy')
assert.equal(proxyMigrate?.value, ownProxy, 'proxy_uid 等于当前 uid 时应允许回退全局代理')
assert.deepEqual(store.saveCalls, [], '已有归属时无需再做一次性迁移')
})
test('test_secret_store_backfills_shared_global_proxy_whitelist', async (t) => {
const { localStorage } = setupWindow()
localStorage.setItem('uid', '43')
clearApiSecretCache()
const sharedProxy = 'https://api.jikip.com/ip-get?num=1&key=shared'
attachConfigStore({
proxy_url: sharedProxy,
proxy_uid: '42',
proxy_shared_uids: ['43'],
})
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
return okResponse({ migrated: 1 })
}
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
})
await loadApiSecrets({ force: true })
const proxyMigrate = migratePayloads
.flatMap((payload) => payload.items || [])
.find((item) => item.moduleKey === 'proxy')
assert.equal(proxyMigrate?.value, sharedProxy, '显式共享白名单内的账号可以回退全局代理')
})
test('test_secret_store_capture_times_out_instead_of_blocking_logout', async () => {
const { localStorage } = setupWindow()
clearApiSecretCache()
localStorage.setItem('username', 'alice')
seedDesktopMirror(localStorage, '42', 'appearance-patent', 'sk-alice-appearance')
const saveCalls: Array<Record<string, unknown>> = []
// 原生桥卡死:read_config 永不返回。capture 自身必须超时,否则登录页会一直停在清理中
attachDesktopBridge(
(() => new Promise(() => {})) as unknown as () => Record<string, unknown>,
(patch) => {
saveCalls.push(patch)
return patch
},
)
const start = Date.now()
await captureApiSecretsForInheritance()
assert.ok(Date.now() - start < 5000, 'capture 超时必须及时返回,不能拖住登出清理')
const saved = saveCalls[0]?.api_secret_inherit as Record<string, unknown> | undefined
assert.equal(saved?.fromUid, '42', '读配置超时也不影响把已取到的密钥留成本机快照')
assert.equal(saved?.proxyUrl, '', '读不到配置时不写代理,避免把不确定的出口留给下一个账号')
})
test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
setupWindow()
clearApiSecretCache()