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 { openAdminConfirm } from '@/components/admin-confirm'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue' import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import { import {
GATING_COUNTRIES, GATING_COUNTRIES,
GATING_SOURCES, GATING_SOURCES,
@@ -50,6 +51,10 @@ const batchText = ref('')
const importBusy = ref(false) const importBusy = ref(false)
const busyRowId = ref(0) const busyRowId = ref(0)
// 快速改筛选/翻页时先发的请求可能后返回;列表与统计各一个序号闸(CR-27)
const pageGate = createLatestRequestGate()
const statsGate = createLatestRequestGate()
const countryOptions = GATING_COUNTRIES.filter((country) => country !== '全部') const countryOptions = GATING_COUNTRIES.filter((country) => country !== '全部')
const typeOptions = GATING_TYPES const typeOptions = GATING_TYPES
@@ -72,30 +77,37 @@ function feedback(message: string, kind: AdminFeedbackKind): void {
} }
async function loadStats(): Promise<void> { async function loadStats(): Promise<void> {
const token = statsGate.begin()
statsLoading.value = true statsLoading.value = true
statsError.value = '' statsError.value = ''
try { try {
stats.value = await fetchBrandGatingStats() const result = await fetchBrandGatingStats()
if (!statsGate.isCurrent(token)) return
stats.value = result
} catch (error) { } catch (error) {
if (!statsGate.isCurrent(token)) return
statsError.value = actionableErrorText(error) statsError.value = actionableErrorText(error)
} finally { } finally {
statsLoading.value = false if (statsGate.isCurrent(token)) statsLoading.value = false
} }
} }
async function loadPage(nextPage = page.value): Promise<void> { async function loadPage(nextPage = page.value): Promise<void> {
const token = pageGate.begin()
pageLoading.value = true pageLoading.value = true
loadError.value = '' loadError.value = ''
try { try {
const result = await fetchBrandGatingPage(filter, nextPage, pageSize.value) const result = await fetchBrandGatingPage(filter, nextPage, pageSize.value)
if (!pageGate.isCurrent(token)) return
rows.value = result.rows rows.value = result.rows
total.value = result.total total.value = result.total
page.value = nextPage page.value = nextPage
loaded.value = true loaded.value = true
} catch (error) { } catch (error) {
if (!pageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error) loadError.value = actionableErrorText(error)
} finally { } 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 { actionableErrorText } from '@/components/admin-feedback'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue' import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import { import {
KEYWORD_USAGE_PAGE_SIZE,
KEYWORD_USAGE_SCENES, KEYWORD_USAGE_SCENES,
createKeywordUsageFilter, createKeywordUsageFilter,
keywordUsageCountsText, keywordUsageCountsText,
@@ -40,16 +42,21 @@ const overviewLoading = ref(false)
const usageRows = ref<KeywordUsageRow[]>([]) const usageRows = ref<KeywordUsageRow[]>([])
const usageTotal = ref(0) const usageTotal = ref(0)
const usagePage = ref(1) 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 usageCounts = ref<KeywordUsageCounts>({ copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 })
const usageLoading = ref(false) const usageLoading = ref(false)
const deleteRows = ref<KeywordUsageRow[]>([]) const deleteRows = ref<KeywordUsageRow[]>([])
const deleteTotal = ref(0) const deleteTotal = ref(0)
const deletePage = ref(1) const deletePage = ref(1)
const deletePageSize = ref(15) const deletePageSize = ref(KEYWORD_USAGE_PAGE_SIZE)
const deleteLoading = ref(false) const deleteLoading = ref(false)
// 切公司/快速改筛选时,先发的请求可能后返回;每个加载口径各一个序号闸(CR-27)
const overviewGate = createLatestRequestGate()
const usageGate = createLatestRequestGate()
const deleteGate = createLatestRequestGate()
const statsCards = computed(() => { const statsCards = computed(() => {
const stats = overview.value?.stats const stats = overview.value?.stats
return [ return [
@@ -76,42 +83,52 @@ function queryParams() {
} }
async function loadOverview(): Promise<void> { async function loadOverview(): Promise<void> {
const token = overviewGate.begin()
overviewLoading.value = true overviewLoading.value = true
try { 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) { } catch (error) {
if (!overviewGate.isCurrent(token)) return
loadError.value = actionableErrorText(error) loadError.value = actionableErrorText(error)
} finally { } finally {
overviewLoading.value = false if (overviewGate.isCurrent(token)) overviewLoading.value = false
} }
} }
async function loadUsage(page = usagePage.value): Promise<void> { async function loadUsage(page = usagePage.value): Promise<void> {
const token = usageGate.begin()
usageLoading.value = true usageLoading.value = true
try { try {
const result = await fetchKeywordUsage({ ...queryParams(), page, pageSize: usagePageSize.value }) const result = await fetchKeywordUsage({ ...queryParams(), page, pageSize: usagePageSize.value })
if (!usageGate.isCurrent(token)) return
usageRows.value = result.rows usageRows.value = result.rows
usageTotal.value = result.total usageTotal.value = result.total
usageCounts.value = result.counts usageCounts.value = result.counts
usagePage.value = page usagePage.value = page
} catch (error) { } catch (error) {
if (!usageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error) loadError.value = actionableErrorText(error)
} finally { } finally {
usageLoading.value = false if (usageGate.isCurrent(token)) usageLoading.value = false
} }
} }
async function loadDeletes(page = deletePage.value): Promise<void> { async function loadDeletes(page = deletePage.value): Promise<void> {
const token = deleteGate.begin()
deleteLoading.value = true deleteLoading.value = true
try { try {
const result = await fetchKeywordUsageDeletes({ ...queryParams(), page, pageSize: deletePageSize.value }) const result = await fetchKeywordUsageDeletes({ ...queryParams(), page, pageSize: deletePageSize.value })
if (!deleteGate.isCurrent(token)) return
deleteRows.value = result.rows deleteRows.value = result.rows
deleteTotal.value = result.total deleteTotal.value = result.total
deletePage.value = page deletePage.value = page
} catch (error) { } catch (error) {
if (!deleteGate.isCurrent(token)) return
loadError.value = actionableErrorText(error) loadError.value = actionableErrorText(error)
} finally { } 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 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 { export function createKeywordUsageFilter(): KeywordUsageFilter {
return { user: '', country: '', keyword: '', scene: '' } 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 test from 'node:test'
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { import {
KEYWORD_USAGE_PAGE_SIZE,
createKeywordUsageFilter, createKeywordUsageFilter,
keywordUsageCountsText, keywordUsageCountsText,
keywordUsageSceneLabel, keywordUsageSceneLabel,
@@ -8,6 +9,12 @@ import {
parseKeywordUsagePage, parseKeywordUsagePage,
} from '../src/pages/tasks/keyword-usage-model.ts' } 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', () => { test('keyword_usage_filter_defaults_and_scene_labels', () => {
assert.deepEqual(createKeywordUsageFilter(), { user: '', country: '', keyword: '', scene: '' }) assert.deepEqual(createKeywordUsageFilter(), { user: '', country: '', keyword: '', scene: '' })
assert.equal(keywordUsageSceneLabel('复制关键词'), '已使用(复制)') 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> <span>自动登录</span>
</label> </label>
</div> </div>
<button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn"> <button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn || logoutCleanupPending">
{{ loggingIn ? '登录中...' : '登录' }} {{ loggingIn ? '登录中...' : logoutCleanupPending ? '正在退出...' : '登录' }}
</button> </button>
</form> </form>
</div> </div>
@@ -136,6 +136,11 @@ const username = ref('')
const password = ref('') const password = ref('')
const passwordVisible = ref(false) const passwordVisible = ref(false)
const loggingIn = ref(false) const loggingIn = ref(false)
/**
* 登出清理进行中(CR-12):继承快照 capture 有超时,但等它返回前不能允许再提交登录,
* 否则新账号 B 的 token/uid 会被上一轮 clearSignedOutState 删掉。
*/
const logoutCleanupPending = ref(false)
const errorMessage = ref('') const errorMessage = ref('')
const kickedNotice = ref(false) const kickedNotice = ref(false)
const expiredNotice = ref(false) const expiredNotice = ref(false)
@@ -407,7 +412,8 @@ function toggleUpdate() {
} }
async function submitLogin() { async function submitLogin() {
if (loggingIn.value) return // 登出清理未完成时禁止提交:清理函数会删 token/uid,晚到的登录会被它清掉(CR-12)
if (loggingIn.value || logoutCleanupPending.value) return
const account = username.value.trim() const account = username.value.trim()
if (!account || !password.value) { if (!account || !password.value) {
errorMessage.value = '请输入账号和密码' errorMessage.value = '请输入账号和密码'
@@ -480,7 +486,9 @@ async function submitLogin() {
onMounted(() => { onMounted(() => {
const params = new URLSearchParams(window.location.search || '') const params = new URLSearchParams(window.location.search || '')
if (params.get('logout') === '1' || params.get('switch') === '1') { if (params.get('logout') === '1' || params.get('switch') === '1') {
logoutCleanupPending.value = true
const clearSignedOutState = () => { const clearSignedOutState = () => {
logoutCleanupPending.value = false
// 清缓存必须在移除 uid 之前:镜像键带 uid,反序会按 uid=0 删错位置, // 清缓存必须在移除 uid 之前:镜像键带 uid,反序会按 uid=0 删错位置,
// 把本账号的明文镜像留在磁盘上给下一个账号(或网页脚本)读到。 // 把本账号的明文镜像留在磁盘上给下一个账号(或网页脚本)读到。
clearApiSecretCache() clearApiSecretCache()
@@ -33,14 +33,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router' 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 ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
import NotificationBell from '@/shared/components/NotificationBell.vue' import NotificationBell from '@/shared/components/NotificationBell.vue'
import { import {
confirmApiSecretInheritance,
declineApiSecretInheritance,
getPendingApiSecretInheritance,
getStoredApiSecretSnapshot, getStoredApiSecretSnapshot,
listApiSecretModules, listApiSecretModules,
loadApiSecrets, loadApiSecrets,
takeApiSecretInheritanceNotice, takeApiSecretInheritanceNotice,
type ApiSecretInheritanceNotice,
type ApiSecretModuleKey, type ApiSecretModuleKey,
} from '@/shared/utils/api-secret-store' } from '@/shared/utils/api-secret-store'
@@ -51,22 +55,71 @@ const submitting = ref(false)
const username = ref('') const username = ref('')
const hint = 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(() => { onMounted(() => {
try { try {
username.value = window.localStorage.getItem('username') || '' username.value = window.localStorage.getItem('username') || ''
} catch { } catch {
/* 忽略存储异常 */ /* 忽略存储异常 */
} }
const inherited = takeApiSecretInheritanceNotice() void promptPendingInheritance()
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}」的密钥配置,请点击上方「检测」逐项确认后保存进入。`
}
}) })
/** /**
@@ -74,7 +74,14 @@ export interface DesktopConfigUpdate {
proxy_url?: string; proxy_url?: string;
proxy_mode?: ProxyMode; proxy_mode?: ProxyMode;
current_uid?: string; 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 }>; proxy_users?: Record<string, { proxy_url?: string; proxy_mode?: number }>;
/** 本机继承快照的作用域标记(CR-12:同一 app.json 才能继承)。 */
api_secret_os_scope?: string;
/** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */ /** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */
api_secret_inherit?: Record<string, unknown> | null; api_secret_inherit?: Record<string, unknown> | null;
aliprice_usename?: string; 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: * 这里不直接读写密钥镜像或服务端接口,全部经 host 回调交给 api-secret-store:
* 两边共用同一份内存/镜像与「当前账号」,又不会互相 import 成环。 * 两边共用同一份内存/镜像与「当前账号」,又不会互相 import 成环。
* 只服务桌面客户端(由 host.isDesktopStorage 判定);网页形态不参与。 * 只服务桌面客户端(由 host.isDesktopStorage 判定);网页形态不参与。
*/ */
import { migrateMyApiSecrets, type UserApiSecretItem } from '../api/types/modules/user-secret.ts' import { migrateMyApiSecrets, type UserApiSecretItem } from '../api/types/modules/user-secret.ts'
import { withTimeout } from './promise-timeout.ts'
export type SecretProxyMode = 1 | 2 export type SecretProxyMode = 1 | 2
@@ -17,8 +26,19 @@ export interface ApiSecretInheritanceNotice {
proxy: boolean proxy: boolean
} }
/** 待确认的继承快照摘要:设置页据此弹确认框,确认前不写服务端。 */
export interface PendingApiSecretInheritance {
fromUid: string
fromUsername: string
savedAt: number
moduleKeys: string[]
proxy: boolean
}
export interface ApiSecretInheritanceHost { export interface ApiSecretInheritanceHost {
currentUid(): string currentUid(): string
/** 登出/切号/清缓存都会 +1;与 uid 一起作为「响应是否还属于当前会话」的判据。 */
currentEpoch(): number
isDesktopStorage(): boolean isDesktopStorage(): boolean
/** 参与继承的模块 key(服务端必填清单 + 默认清单)。 */ /** 参与继承的模块 key(服务端必填清单 + 默认清单)。 */
moduleKeys(): Set<string> moduleKeys(): Set<string>
@@ -35,107 +55,191 @@ export interface ApiSecretInheritanceHost {
export interface InheritanceOutcome { export interface InheritanceOutcome {
count: number count: number
notice: ApiSecretInheritanceNotice | null notice: ApiSecretInheritanceNotice | null
/** 快照是否已被消费/清掉;false 表示会话已变或失败,调用方应保留 pending 以便重试。 */
cleared: boolean
} }
type InheritedSecretStash = { export type InheritedSecretStash = {
schema: 1 schema: 2
fromUid: string fromUid: string
fromUsername: string fromUsername: string
savedAt: number savedAt: number
osUserScope: string
secrets: Record<string, string> secrets: Record<string, string>
proxyUrl: string proxyUrl: string
proxyMode: SecretProxyMode proxyMode: SecretProxyMode
} }
export type InheritanceStashRead =
| { state: 'none' }
| { state: 'invalid' }
| { state: 'valid'; stash: InheritedSecretStash }
const INHERIT_STASH_KEY = 'api_secret_inherit' 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 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, config: Record<string, unknown> | null | undefined,
allowed: Set<string>, allowed: Set<string>,
): InheritedSecretStash | null { ): InheritanceStashRead {
const raw = config?.[INHERIT_STASH_KEY] const raw = config?.[INHERIT_STASH_KEY]
if (!raw || typeof raw !== 'object') return null if (raw == null) return { state: 'none' }
const record = raw as Record<string, unknown> const record = asRecord(raw)
if (record.schema !== 1) return null if (!record) return { state: 'invalid' }
const fromUid = typeof record.fromUid === 'string' ? record.fromUid.trim() : '' if (record.schema !== INHERIT_SCHEMA) return { state: 'invalid' }
const fromUid = text(record.fromUid)
const savedAt = typeof record.savedAt === 'number' ? record.savedAt : 0 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> = {} const secrets: Record<string, string> = {}
if (record.secrets && typeof record.secrets === 'object') { for (const [moduleKey, value] of Object.entries(secretRecord)) {
for (const [moduleKey, value] of Object.entries(record.secrets as Record<string, unknown>)) { if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) {
if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) { secrets[moduleKey] = value.trim()
secrets[moduleKey] = value.trim()
}
} }
} }
const proxyUrl = text(proxyRaw)
if (!Object.keys(secrets).length && !proxyUrl) return { state: 'invalid' }
return { return {
schema: 1, state: 'valid',
fromUid, stash: {
fromUsername: typeof record.fromUsername === 'string' ? record.fromUsername.trim() : '', schema: 2,
savedAt, fromUid,
secrets, fromUsername: text(record.fromUsername),
proxyUrl: typeof record.proxyUrl === 'string' ? record.proxyUrl.trim() : '', savedAt,
proxyMode: Number(record.proxyMode) === 2 ? 2 : 1, 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 被移除之前调用。 * 调用方必须在本页内存/本地镜像被清掉、且 uid 被移除之前调用。
*/ */
export async function captureSecretsForInheritance(host: ApiSecretInheritanceHost): Promise<void> { export async function captureSecretsForInheritance(host: ApiSecretInheritanceHost): Promise<void> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return if (typeof window === 'undefined' || !host.isDesktopStorage()) return
const uid = host.currentUid() const uid = host.currentUid()
if (uid === '0') return if (uid === '0') return
const epoch = host.currentEpoch()
const secrets: Record<string, string> = {} const secrets: Record<string, string> = {}
for (const moduleKey of host.moduleKeys()) { for (const moduleKey of host.moduleKeys()) {
const value = host.readSecret(moduleKey).trim() const value = host.readSecret(moduleKey).trim()
if (value) secrets[moduleKey] = value if (value) secrets[moduleKey] = value
} }
const config = await host.readConfig().catch((error) => { const config = await withTimeout(host.readConfig(), BRIDGE_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 登出时读取本机代理失败,继承快照将不含代理:', error) console.warn('[api-secret] 登出时读取本机配置失败,继承快照将不含代理:', error)
return null return null
}) })
// 等配置期间可能已经被登出清理:旧账号的快照不能盖到新账号的作用域上
if (!sessionCurrent(host, uid, epoch)) return
const proxy = host.readLocalProxy(config, uid) const proxy = host.readLocalProxy(config, uid)
const osUserScope = readOsUserScope(config) || newOsScope()
const stash: InheritedSecretStash | null = Object.keys(secrets).length || proxy.url const stash: InheritedSecretStash | null = Object.keys(secrets).length || proxy.url
? { ? {
schema: 1, schema: 2,
fromUid: uid, fromUid: uid,
fromUsername: window.localStorage.getItem('username') || '', fromUsername: window.localStorage.getItem('username') || '',
savedAt: Date.now(), savedAt: Date.now(),
osUserScope,
secrets, secrets,
proxyUrl: proxy.url, proxyUrl: proxy.url,
proxyMode: proxy.mode, proxyMode: proxy.mode,
} }
: null : null
await host.saveConfig({ [INHERIT_STASH_KEY]: stash }).catch((error) => { await withTimeout(host.saveConfig({ [OS_SCOPE_KEY]: osUserScope, [INHERIT_STASH_KEY]: stash }), BRIDGE_TIMEOUT_MS)
console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error) .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,后台锁定的代理不会被顶掉)。 * (服务端 migrate 接口本身也是 fill-only,后台锁定的代理不会被顶掉)。
* 检测状态不继承:那不是配置,不能跨账号冒充已通过。 * 检测状态不继承:那不是配置,不能跨账号冒充已通过。
*
* 每个 await 之后都同时比 uid 与 epoch:确认框打开期间用户可能已经切号/登出,
* 晚到的 migrate 响应或写回都不能落到新账号。
*/ */
export async function inheritSecretsFromDevice( export async function applyInheritedSecrets(
host: ApiSecretInheritanceHost, host: ApiSecretInheritanceHost,
stash: InheritedSecretStash,
config: Record<string, unknown> | null | undefined,
serverItems: UserApiSecretItem[], serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined, serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<InheritanceOutcome> { ): 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() const uid = host.currentUid()
if (uid === '0') return { count: 0, notice: null } if (uid === '0') return { count: 0, notice: null, cleared: false }
const config = await host.readConfig().catch((error) => { const epoch = host.currentEpoch()
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 }
const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey)) const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey))
const pending: Array<{ moduleKey: string; value: string }> = [] const pending: Array<{ moduleKey: string; value: string }> = []
for (const [moduleKey, value] of Object.entries(stash.secrets)) { 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) const inheritProxy = Boolean(stash.proxyUrl)
&& Boolean(config)
&& !serverProxyItem?.exists && !serverProxyItem?.exists
&& !host.readLocalProxy(config, uid).url && !serverProxyItem?.locked
&& !ownProxy
if (inheritProxy) pending.push({ moduleKey: 'proxy', value: stash.proxyUrl }) if (inheritProxy) pending.push({ moduleKey: 'proxy', value: stash.proxyUrl })
if (!pending.length) { if (!pending.length) {
await host.saveConfig({ [INHERIT_STASH_KEY]: null }).catch((error) => { await clearInheritedSecrets(host)
console.warn('[api-secret] 清理已无用的继承快照失败:', error) return { count: 0, notice: null, cleared: true }
})
return { count: 0, notice: null }
} }
const result = await migrateMyApiSecrets(pending).catch((error) => { const result = await migrateMyApiSecrets(pending).catch((error) => {
console.warn('[api-secret] 继承本机账号密钥失败(下次加载重试):', error) console.warn('[api-secret] 继承本机账号密钥失败(下次确认时重试):', error)
return null return null
}) })
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
const migrated = Number(result?.migrated || 0) 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) { for (const item of pending) {
if (item.moduleKey !== 'proxy') host.writeSecret(item.moduleKey, item.value) if (item.moduleKey !== 'proxy') host.writeSecret(item.moduleKey, item.value)
} }
@@ -169,12 +277,13 @@ export async function inheritSecretsFromDevice(
await host.saveConfig(patch).catch((error) => { await host.saveConfig(patch).catch((error) => {
console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error) console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error)
}) })
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
const notice: ApiSecretInheritanceNotice = { const notice: ApiSecretInheritanceNotice = {
fromUid: stash.fromUid, fromUid: stash.fromUid,
fromUsername: stash.fromUsername, fromUsername: stash.fromUsername,
moduleKeys: pending.filter((item) => item.moduleKey !== 'proxy').map((item) => item.moduleKey), moduleKeys: pending.filter((item) => item.moduleKey !== 'proxy').map((item) => item.moduleKey),
proxy: inheritProxy, proxy: inheritProxy,
} }
console.log(`[api-secret] 已继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`) console.log(`[api-secret] 已确认继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`)
return { count: migrated, notice } return { count: migrated, notice, cleared: true }
} }
+283 -56
View File
@@ -23,15 +23,24 @@ import {
type UserApiSecretItem, type UserApiSecretItem,
} from '../api/types/modules/user-secret.ts' } from '../api/types/modules/user-secret.ts'
import { import {
applyInheritedSecrets,
captureSecretsForInheritance, captureSecretsForInheritance,
inheritSecretsFromDevice, clearInheritedSecrets,
readInheritedSecretStash,
toPendingInheritance,
type ApiSecretInheritanceHost, type ApiSecretInheritanceHost,
type ApiSecretInheritanceNotice, type ApiSecretInheritanceNotice,
type InheritedSecretStash,
type PendingApiSecretInheritance,
} from './api-secret-inheritance.ts' } from './api-secret-inheritance.ts'
import { withTimeout } from './promise-timeout.ts'
import type { DesktopConfigUpdate } from '../bridges/pywebview.ts' import type { DesktopConfigUpdate } from '../bridges/pywebview.ts'
export type { ApiSecretModuleKey, ApiSecretCheckStatus } export type { ApiSecretModuleKey, ApiSecretCheckStatus }
export type { ApiSecretInheritanceNotice } from './api-secret-inheritance.ts' export type {
ApiSecretInheritanceNotice,
PendingApiSecretInheritance,
} from './api-secret-inheritance.ts'
export type { UserApiSecretCheckResult } 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 MIGRATED_FLAG_PREFIX = 'brand:api-secret-migrated'
const DEFAULT_REQUIRED_MODULES: ApiSecretModuleKey[] = ['appearance-patent', 'similar-asin'] const DEFAULT_REQUIRED_MODULES: ApiSecretModuleKey[] = ['appearance-patent', 'similar-asin']
const FETCH_TIMEOUT_MS = 4000 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 memory = new Map<string, ApiSecretCacheEntry>()
const listeners = new Set<() => void>() const listeners = new Set<() => void>()
@@ -101,6 +114,14 @@ let inflightLoad: Promise<ApiSecretLoadState> | null = null
let serverProxy: ServerProxySnapshot | null = null let serverProxy: ServerProxySnapshot | null = null
/** 本次登录继承到的配置摘要:设置页消费一次,不落盘(避免多一个明文旁路)。 */ /** 本次登录继承到的配置摘要:设置页消费一次,不落盘(避免多一个明文旁路)。 */
let inheritanceNotice: ApiSecretInheritanceNotice | null = null let inheritanceNotice: ApiSecretInheritanceNotice | null = null
/**
* 本机上一个账号留下、等待用户显式确认的继承快照(CR-12)。
* 确认前不写服务端、不写本地镜像;登出/切号时连同摘要一起作废。
*/
let pendingInheritance: {
summary: PendingApiSecretInheritance
stash: InheritedSecretStash
} | null = null
/** 登出/切号会让在飞的密钥加载失效,防止 A 的响应落到 B 的会话里。 */ /** 登出/切号会让在飞的密钥加载失效,防止 A 的响应落到 B 的会话里。 */
let cacheEpoch = 0 let cacheEpoch = 0
/** 上一次读到的登录 uid:会话过期后直接换号登录时,内存里的旧账号明文必须就地作废。 */ /** 上一次读到的登录 uid:会话过期后直接换号登录时,内存里的旧账号明文必须就地作废。 */
@@ -115,12 +136,18 @@ function currentUid(): string {
inflightLoad = null inflightLoad = null
serverProxy = null serverProxy = null
inheritanceNotice = null inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1 cacheEpoch += 1
} }
cachedUid = uid cachedUid = uid
return uid return uid
} }
/** 响应回写前的统一闸门:uid 与 epoch 必须同时还是发起请求时那一个。 */
function sessionCurrent(uid: string, epoch: number): boolean {
return currentUid() === uid && cacheEpoch === epoch
}
function buildMirrorKey(moduleKey: string) { function buildMirrorKey(moduleKey: string) {
return `${MIRROR_PREFIX}:${currentUid()}:${moduleKey}` return `${MIRROR_PREFIX}:${currentUid()}:${moduleKey}`
} }
@@ -412,8 +439,12 @@ export function ensureApiSecretsLoaded(): Promise<ApiSecretLoadState> {
async function applyServerBundle( async function applyServerBundle(
bundle: UserApiSecretBundle | null | undefined, bundle: UserApiSecretBundle | null | undefined,
uid: string,
epoch: number, epoch: number,
): Promise<void> { ): Promise<void> {
// 先用调用方发请求时的 uid/epoch 验身,再动内存/镜像:
// 不能在这里重新 currentUid()——那会把「已经换成 B」当成合法会话,把 A 的包写进 B。
if (!sessionCurrent(uid, epoch)) return
if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) { if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) {
requiredModules = bundle.requiredModules requiredModules = bundle.requiredModules
} }
@@ -424,54 +455,50 @@ async function applyServerBundle(
} }
serverProxy = toServerProxy(bundle?.proxy) serverProxy = toServerProxy(bundle?.proxy)
// 登出/换号可能发生在读配置的等待里:旧账号的锁定代理绝不能写进新账号的本地配置 // 登出/换号可能发生在读配置的等待里:旧账号的锁定代理绝不能写进新账号的本地配置
if (epoch !== cacheEpoch) return if (!sessionCurrent(uid, epoch)) return
if (serverProxy?.locked && serverProxy.full) { 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> { async function doLoad(): Promise<ApiSecretLoadState> {
// 换号(含会话过期后直接登录 B)时先作废旧账号缓存,再取 epoch: // 换号(含会话过期后直接登录 B)时先作废旧账号缓存,再取 epoch:
// 反序会把本次加载自己判成“过期响应”,继承与门禁都走不到。 // 反序会把本次加载自己判成“过期响应”,继承与门禁都走不到。
currentUid() const uid = currentUid()
const epoch = cacheEpoch const epoch = cacheEpoch
try { try {
let bundle = await fetchMyApiSecrets() let bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, epoch) await applyServerBundle(bundle, uid, epoch)
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
bundleLoaded = true bundleLoaded = true
notify() notify()
const migrated = await tryMigrateLocalSecrets(bundle?.items || []) const migrated = await tryMigrateLocalSecrets(bundle?.items || [], uid, epoch)
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
if (migrated > 0) { if (migrated > 0) {
bundle = await fetchMyApiSecrets() bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, epoch) await applyServerBundle(bundle, uid, epoch)
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
notify() notify()
} }
// 继承必须排在旧本地密钥迁移之后:两者都走 fill-only,谁先占住服务端空缺谁生效, // 继承必须排在旧本地密钥迁移之后:两者都走 fill-only,谁先占住服务端空缺谁生效,
// 而当前账号自己的旧记录理应优先于上一个账号留下的快照。 // 而当前账号自己的旧记录理应优先于上一个账号留下的快照。
// CR-12:这里只登记待确认快照,不再自动 migrate——明文是否跨账号复用必须由用户拍板。
if (bundle && Array.isArray(bundle.items)) { if (bundle && Array.isArray(bundle.items)) {
const inherited = await tryInheritSecretsFromDevice(bundle.items, bundle.proxy) await stageInheritance(bundle.items, bundle.proxy, uid, epoch)
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
if (inherited > 0) {
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
notify()
}
} }
const backfilled = await tryBackfillProxyToServer() const backfilled = await tryBackfillProxyToServer(uid, epoch)
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
if (backfilled) { if (backfilled) {
// 补报已写入服务端:重拉一次让 serverProxy 反映新状态, // 补报已写入服务端:重拉一次让 serverProxy 反映新状态,
// 否则任务提交前的代理检查会拿到上一轮的空快照。 // 否则任务提交前的代理检查会拿到上一轮的空快照。
const refreshed = await fetchMyApiSecrets() const refreshed = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown' if (!sessionCurrent(uid, epoch)) return 'unknown'
serverProxy = toServerProxy(refreshed?.proxy) serverProxy = toServerProxy(refreshed?.proxy)
notify() 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 if (typeof window === 'undefined') return 0
try { try {
if (window.localStorage.getItem(migratedFlagKey()) === '1') { if (window.localStorage.getItem(migratedFlagKey()) === '1') {
@@ -505,6 +536,8 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
return 0 return 0
} }
const result = await migrateMyApiSecrets(pending) const result = await migrateMyApiSecrets(pending)
// 等接口期间可能已登出/切号:旧账号的明文不能再写进当前账号的本地镜像
if (!sessionCurrent(uid, epoch)) return 0
const migrated = Number(result?.migrated || 0) const migrated = Number(result?.migrated || 0)
// 迁移成功后本地保留明文(供提交任务直接使用),只清理旧记录与标记 // 迁移成功后本地保留明文(供提交任务直接使用),只清理旧记录与标记
for (const item of pending) { for (const item of pending) {
@@ -527,17 +560,25 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
* *
* @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。 * @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。
*/ */
async function tryBackfillProxyToServer(): Promise<boolean> { async function tryBackfillProxyToServer(uid: string, epoch: number): Promise<boolean> {
try { try {
const uid = currentUid()
if (uid === '0') return false 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 (!config) return false
// 等配置期间可能已经登出/换号:补报请求会带新账号令牌,必须放弃旧账号的本地代理 // 等配置期间可能已经登出/换号:补报请求会带新账号令牌,必须放弃旧账号的本地代理
if (currentUid() !== uid) return false if (!sessionCurrent(uid, epoch)) return false
const url = readLocalProxyUrl(config) // 升级一次性归属迁移:老版本只存全局 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 if (!url) return false
const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }]) const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }])
if (!sessionCurrent(uid, epoch)) return false
return Number(result?.migrated || 0) > 0 return Number(result?.migrated || 0) > 0
} catch (error) { } catch (error) {
console.warn('[api-secret] 代理配置补报失败(下次加载重试):', 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 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。 * 无归属的全局 proxy_url 一次性归给当前 uid(CR-04)。
* 回退口径与客户端任务链 `resolve_current_proxy` 一致——老版本把代理存在全局 proxy_url, *
* 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在 * 老版本把代理存在全局 proxy_url(2026-10-25 账号 1210 的 32300/32309 就靠这条路径补报),
* 商标维度整批判失败(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( function readLocalProxyEntry(
config: Record<string, unknown> | null | undefined, config: Record<string, unknown> | null | undefined,
uid = currentUid(), uid = currentUid(),
): { url: string; mode: 1 | 2 } { ): { url: string; mode: 1 | 2 } {
if (!config) return { url: '', mode: 1 } 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') { if (uid !== '0') {
const users = (config.proxy_users ?? {}) as Record<string, unknown> const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) 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: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
} }
} }
return { const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
url: typeof config.proxy_url === 'string' ? config.proxy_url.trim() : '', const shared = isSharedProxy(config, uid)
mode: Number(config.proxy_mode) === 2 ? 2 : 1, 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 { function readLocalProxyUrl(
return readLocalProxyEntry(config).url config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): string {
return readLocalProxyEntry(config, uid).url
} }
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null { function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
@@ -615,15 +746,18 @@ function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxy
* 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。 * 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。
* 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。 * 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。
*/ */
async function syncLockedProxyToLocal(full: string): Promise<void> { async function syncLockedProxyToLocal(
full: string,
uidAtStart: string,
epochAtStart: number,
): Promise<void> {
try { try {
if (typeof window === 'undefined') return if (typeof window === 'undefined') return
const api = window.pywebview?.api const api = window.pywebview?.api
if (!api?.read_config || !api?.save_config) return if (!api?.read_config || !api?.save_config) return
const uidAtStart = currentUid()
const config = (await api.read_config()) as Record<string, unknown> | null const config = (await api.read_config()) as Record<string, unknown> | null
if (currentUid() !== uidAtStart) return if (!sessionCurrent(uidAtStart, epochAtStart)) return
if (readLocalProxyUrl(config) === full) return if (readLocalProxyUrl(config, uidAtStart) === full) return
const uid = uidAtStart const uid = uidAtStart
if (uid === '0') { if (uid === '0') {
const mode = Number(config?.proxy_mode) === 2 ? 2 : 1 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 级合并(保留其他用户),故同一对象内要带齐原有模式 // save_config 对 proxy_users 只做 uid 级合并(保留其他用户),故同一对象内要带齐原有模式
const mode = Number(own.proxy_mode) === 2 ? 2 : 1 const mode = Number(own.proxy_mode) === 2 ? 2 : 1
await api.save_config({ proxy_users: { [uid]: { proxy_url: full, proxy_mode: mode } } }) await api.save_config({ proxy_users: { [uid]: { proxy_url: full, proxy_mode: mode } } })
// save 的 await 之后不再有写操作;保留一次检查让"迟到响应不落到新账号"的口径可被测试钉住
if (!sessionCurrent(uidAtStart, epochAtStart)) return
} catch (error) { } catch (error) {
console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error) console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error)
} }
@@ -642,40 +778,130 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
const inheritanceHost: ApiSecretInheritanceHost = { const inheritanceHost: ApiSecretInheritanceHost = {
currentUid, currentUid,
currentEpoch: () => cacheEpoch,
isDesktopStorage: isNativeDesktopStorage, isDesktopStorage: isNativeDesktopStorage,
moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]), moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]),
readSecret: (moduleKey) => readEntry(moduleKey).value, readSecret: (moduleKey) => readEntry(moduleKey).value,
// 只有 applyInheritedSecrets 在 migrate 的 await 之后重新比过 uid/epoch 才会调到这里
writeSecret: (moduleKey, value) => { writeSecret: (moduleKey, value) => {
const entry = readEntry(moduleKey) const entry = readEntry(moduleKey)
updateEntry(moduleKey, { value: entry.value || value }) updateEntry(moduleKey, { value: entry.value || value })
}, },
readConfig: () => readConfigForBackfill(), readConfig: () => readConfigForBackfill(),
saveConfig: async (patch) => { saveConfig: (patch) => saveConfigForBackfill(patch),
const api = window.pywebview?.api
if (!api?.save_config) return
await Promise.resolve(api.save_config(patch as DesktopConfigUpdate))
},
readLocalProxy: readLocalProxyEntry, readLocalProxy: readLocalProxyEntry,
} }
/** /**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。 * 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号**确认后**继承。
* *
* 只走桌面真实桥(网页形态没有本地任务链,也不该把明文留给浏览器); * 只走桌面真实桥(网页形态没有本地任务链,也不该把明文留给浏览器);
* 必须在本页内存/本地镜像被 clearApiSecretCache 清掉、且 localStorage.uid 被移除之前调用, * 必须在本页内存/本地镜像被 clearApiSecretCache 清掉、且 localStorage.uid 被移除之前调用,
* 否则读到的会是空值或另一个 uid 的镜像。 * 否则读到的会是空值或另一个 uid 的镜像。
*
* 外层再加一道整体超时:桥卡死时调用方(登录页)必须能继续清 token/uid,
* 不能让登出停在"还在清"的状态里(CR-12)。
*/ */
export function captureApiSecretsForInheritance(): Promise<void> { 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[], serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined, serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<number> { uid: string,
const outcome = await inheritSecretsFromDevice(inheritanceHost, serverItems, serverProxyItem) epoch: number,
if (outcome.notice) inheritanceNotice = outcome.notice ): Promise<void> {
return outcome.count 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 inflightLoad = null
serverProxy = null serverProxy = null
inheritanceNotice = null inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1 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('停用/删除文案必须互不冒充:停用句不说删除、删除句不说停用', () => { test('停用/删除文案必须互不冒充:停用句不说删除、删除句不说停用', () => {
const disabledLine = loginPageSource const disabledLine = loginPageSource
.split('\n') .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 { import {
captureApiSecretsForInheritance, captureApiSecretsForInheritance,
clearApiSecretCache, clearApiSecretCache,
confirmApiSecretInheritance,
declineApiSecretInheritance,
ensureBrandCheckProxy, ensureBrandCheckProxy,
getPendingApiSecretInheritance,
getServerProxySnapshot, getServerProxySnapshot,
getStoredApiSecret, getStoredApiSecret,
getStoredApiSecretSnapshot, getStoredApiSecretSnapshot,
@@ -199,9 +202,18 @@ test('test_secret_store_backfills_legacy_global_proxy_to_server', async (t) => {
clearApiSecretCache() clearApiSecretCache()
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=legacy' const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=legacy'
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = [] 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 let bundleCalls = 0
// 老版本只把代理存在全局 proxy_url,proxy_users 里没有该用户 // 老版本只把代理存在全局 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) => { mockRequest(t, (req) => {
if ((req.url || '').includes('/migrate')) { if ((req.url || '').includes('/migrate')) {
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> }) 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') .find((item) => item.moduleKey === 'proxy')
assert.equal(proxyMigrate?.value, globalUrl, '旧版全局代理应补报到服务端') assert.equal(proxyMigrate?.value, globalUrl, '旧版全局代理应补报到服务端')
assert.equal(getServerProxySnapshot()?.exists, true, '补报后应重拉服务端代理快照') 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) => { 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 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) => { test('test_secret_store_inherits_previous_account_config_on_desktop', async (t) => {
const { localStorage } = setupWindow() const { localStorage } = setupWindow()
clearApiSecretCache() clearApiSecretCache()
@@ -337,6 +397,8 @@ test('test_secret_store_inherits_previous_account_config_on_desktop', async (t)
await captureApiSecretsForInheritance() await captureApiSecretsForInheritance()
const stash = config.api_secret_inherit as Record<string, unknown> | null const stash = config.api_secret_inherit as Record<string, unknown> | null
assert.equal(stash?.fromUid, '42', '登出时应把当前账号配置留成本机继承快照') 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 // 真实登出顺序:先清缓存(此时 uid 仍是 42),再移除 uid;登录 B 后 uid=43
clearApiSecretCache() clearApiSecretCache()
@@ -370,33 +432,44 @@ test('test_secret_store_inherits_previous_account_config_on_desktop', async (t)
await loadApiSecrets({ force: true }) 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 || []) const migrated = migratePayloads.flatMap((payload) => payload.items || [])
assert.equal( assert.equal(
migrated.find((item) => item.moduleKey === 'appearance-patent')?.value, migrated.find((item) => item.moduleKey === 'appearance-patent')?.value,
'sk-alice-appearance', 'sk-alice-appearance',
'上一个账号的外观专利密钥应继承给当前账号', '确认后上一个账号的外观专利密钥应继承给当前账号',
) )
assert.equal( assert.equal(
migrated.find((item) => item.moduleKey === 'similar-asin')?.value, migrated.find((item) => item.moduleKey === 'similar-asin')?.value,
'sk-alice-similar', 'sk-alice-similar',
'上一个账号的货源查询密钥应继承给当前账号', '确认后上一个账号的货源查询密钥应继承给当前账号',
) )
assert.equal( assert.equal(
migrated.find((item) => item.moduleKey === 'proxy')?.value, migrated.find((item) => item.moduleKey === 'proxy')?.value,
aliceProxy, aliceProxy,
'服务端缺代理时应继承上一个账号的代理', '服务端缺代理且未锁定时应继承上一个账号的代理',
) )
assert.equal(getStoredApiSecret('appearance-patent'), 'sk-alice-appearance', '继承后当前账号本地应能直接取到明文') assert.equal(getStoredApiSecret('appearance-patent'), 'sk-alice-appearance', '继承后当前账号本地应能直接取到明文')
const users = config.proxy_users as Record<string, { proxy_url: string; proxy_mode: number }> 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_url, aliceProxy, '继承的代理应写进当前 uid 的本地配置')
assert.equal(users['43'].proxy_mode, 2, '代理模式应一并继承') 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?.fromUid, '42')
assert.equal(notice?.fromUsername, 'alice') assert.equal(notice?.fromUsername, 'alice')
assert.equal(notice?.proxy, true) assert.equal(notice?.proxy, true)
assert.deepEqual(notice?.moduleKeys.slice().sort(), ['appearance-patent', 'similar-asin']) 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) => { 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') localStorage.setItem('uid', '43')
const config: Record<string, unknown> = { const config: Record<string, unknown> = {
current_uid: '43', current_uid: '43',
api_secret_os_scope: 'scope-1',
api_secret_inherit: { api_secret_inherit: {
schema: 1, schema: 2,
fromUid: '42', fromUid: '42',
fromUsername: 'alice', fromUsername: 'alice',
savedAt: Date.now(), savedAt: Date.now(),
osUserScope: 'scope-1',
secrets: { 'appearance-patent': 'sk-alice-appearance', 'similar-asin': 'sk-alice-similar' }, secrets: { 'appearance-patent': 'sk-alice-appearance', 'similar-asin': 'sk-alice-similar' },
proxyUrl: 'https://api.jikip.com/ip-get?num=1&key=alice', proxyUrl: 'https://api.jikip.com/ip-get?num=1&key=alice',
proxyMode: 2, proxyMode: 2,
@@ -441,6 +516,10 @@ test('test_secret_store_inheritance_never_overwrites_existing_account_config', a
await loadApiSecrets({ force: true }) await loadApiSecrets({ force: true })
assert.deepEqual(migratePayloads, [], '用户未确认前不得自动继承')
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42', '应登记待确认快照')
await confirmApiSecretInheritance()
const migrated = migratePayloads.flatMap((payload) => payload.items || []) const migrated = migratePayloads.flatMap((payload) => payload.items || [])
assert.deepEqual( assert.deepEqual(
migrated.map((item) => item.moduleKey), 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(getStoredApiSecret('appearance-patent'), '', '当前账号已有密钥时不得把上一个账号的明文塞进本地')
assert.equal(config.api_secret_inherit, null, '没有需要补的项时也应消费快照') assert.equal(config.api_secret_inherit, null, '继承完成后应消费快照')
assert.equal( assert.equal(
(config.proxy_users as Record<string, unknown> | undefined)?.['43'], (config.proxy_users as Record<string, unknown> | undefined)?.['43'],
undefined, 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) => { test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
setupWindow() setupWindow()
clearApiSecretCache() clearApiSecretCache()