@@ -1508,6 +1545,13 @@ import {
type HeaderOverrideRow
} from '@/components/account/credentialsBuilder'
import GrokBaseUrlPresets from '@/components/account/GrokBaseUrlPresets.vue'
+import OpenAIImageSizeTiersField from '@/components/account/OpenAIImageSizeTiersField.vue'
+import {
+ OPENAI_IMAGE_SIZE_TIERS,
+ OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY,
+ openAIImageSizeTiersPayload,
+ type OpenAIImageSizeTier
+} from '@/components/account/openaiImageSizeTiers'
import {
OPENAI_WS_MODE_CTX_POOL,
OPENAI_WS_MODE_OFF,
@@ -1661,6 +1705,7 @@ const enableGroups = ref(false)
const enableOpenAIPassthrough = ref(false)
const enableOpenAIFlattenNamespaces = ref(false)
const enableOpenAILongContextBilling = ref(false)
+const enableOpenAIImageSizeTiers = ref(false)
const enableOpenAIEndpointCapabilities = ref(false)
const enableOpenAIResponsesMode = ref(false)
const enableOpenAIWSMode = ref(false)
@@ -1697,6 +1742,7 @@ const openaiPassthroughEnabled = ref(false)
// Codex namespace 工具摊平兼容开关(仅 OAuth),缺省关闭即原样保留
const openaiFlattenNamespacesEnabled = ref(false)
const openAILongContextBillingEnabled = ref(false)
+const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS])
const openAIEndpointCapabilities = ref([
'chat_completions',
'embeddings'
@@ -1996,6 +2042,11 @@ const buildUpdatePayload = (): Record | null => {
extra.openai_long_context_billing_enabled = openAILongContextBillingEnabled.value
}
+ if (enableOpenAIImageSizeTiers.value && allOpenAIPassthroughCapable.value) {
+ // extra 按 JSONB 合并写入,不限档位用空列表覆盖旧值。
+ ensureExtra()[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] = openAIImageSizeTiersPayload(openAIImageSizeTiers.value) ?? []
+ }
+
if (applyOpenAIEndpointCapabilities) {
credentials.openai_capabilities =
openAIEndpointCapabilities.value.length === 2 && !openAIEndpointCapabilities.value.includes('seedance')
@@ -2206,6 +2257,7 @@ const handleSubmit = async () => {
enableOpenAIPassthrough.value ||
enableOpenAIFlattenNamespaces.value ||
(enableOpenAILongContextBilling.value && allOpenAIPassthroughCapable.value) ||
+ (enableOpenAIImageSizeTiers.value && allOpenAIPassthroughCapable.value) ||
(enableOpenAIEndpointCapabilities.value && allOpenAIAPIKey.value) ||
(enableOpenAIResponsesMode.value && allOpenAIAPIKey.value) ||
enableModelRestriction.value ||
@@ -2368,6 +2420,7 @@ watch(
enableOpenAIPassthrough.value = false
enableOpenAIFlattenNamespaces.value = false
enableOpenAILongContextBilling.value = false
+ enableOpenAIImageSizeTiers.value = false
enableOpenAIEndpointCapabilities.value = false
enableOpenAIResponsesMode.value = false
enableOpenAIWSMode.value = false
@@ -2386,6 +2439,7 @@ watch(
openaiPassthroughEnabled.value = false
openaiFlattenNamespacesEnabled.value = false
openAILongContextBillingEnabled.value = false
+ openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS]
openAIEndpointCapabilities.value = ['chat_completions', 'embeddings']
openAIResponsesMode.value = 'auto'
modelRestrictionMode.value = 'whitelist'
diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue
index cb013a4dd3..aa27e6e841 100644
--- a/frontend/src/components/account/CreateAccountModal.vue
+++ b/frontend/src/components/account/CreateAccountModal.vue
@@ -3662,6 +3662,14 @@
@@ -4154,6 +4162,12 @@ import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
import Select from '@/components/common/Select.vue'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import UpstreamRequestIdHeaderField from '@/components/account/UpstreamRequestIdHeaderField.vue'
+import OpenAIImageSizeTiersField from '@/components/account/OpenAIImageSizeTiersField.vue'
+import {
+ OPENAI_IMAGE_SIZE_TIERS,
+ applyOpenAIImageSizeTiersToExtra,
+ type OpenAIImageSizeTier
+} from '@/components/account/openaiImageSizeTiers'
import PlatformIcon from '@/components/common/PlatformIcon.vue'
import Icon from '@/components/icons/Icon.vue'
import ProxySelector from '@/components/common/ProxySelector.vue'
@@ -4709,6 +4723,7 @@ const openAICompactMode = ref('auto')
const openAIResponsesMode = ref('auto')
// Images 非流式响应缺 b64_json 时由网关下载 url 回填(仅 OpenAI API Key)。
const openAIImagesUrlToB64JsonEnabled = ref(false)
+const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS])
const openAIEndpointCapabilities = ref(['chat_completions', 'embeddings'])
const openaiOAuthResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF)
const openaiAPIKeyResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF)
@@ -5227,6 +5242,7 @@ watch(
headerOverrideEnabled.value = false
headerOverrideRows.value = []
openAIImagesUrlToB64JsonEnabled.value = false
+ openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS]
grokOAuthCustomBaseUrlEnabled.value = false
grokOAuthBaseUrl.value = ''
// Reset OAuth states
@@ -5663,6 +5679,7 @@ const resetForm = () => {
headerOverrideEnabled.value = false
headerOverrideRows.value = []
openAIImagesUrlToB64JsonEnabled.value = false
+ openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS]
grokOAuthCustomBaseUrlEnabled.value = false
grokOAuthBaseUrl.value = ''
interceptWarmupRequests.value = false
@@ -5807,6 +5824,7 @@ const buildOpenAIExtra = (base?: Record): Record 0 ? extra : undefined
}
diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue
index 9ca560b519..8182d4d7b4 100644
--- a/frontend/src/components/account/EditAccountModal.vue
+++ b/frontend/src/components/account/EditAccountModal.vue
@@ -2243,6 +2243,14 @@
+
+
+
+
+
('auto')
const openAIResponsesMode = ref
('auto')
// Images 非流式响应缺 b64_json 时由网关下载 url 回填(仅 OpenAI API Key)。
const openAIImagesUrlToB64JsonEnabled = ref(false)
+const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS])
const openAIEndpointCapabilities = ref(['chat_completions', 'embeddings'])
const openaiOAuthResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF)
const openaiAPIKeyResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF)
@@ -4630,6 +4646,7 @@ const syncFormFromAccount = (newAccount: Account | null) => {
allowOverages.value = extra?.allow_overages === true
upstreamRequestIdHeader.value = readUpstreamRequestIdHeader(extra)
openAIImagesUrlToB64JsonEnabled.value = extra?.images_url_to_b64_json === true
+ openAIImageSizeTiers.value = readOpenAIImageSizeTiers(extra)
autoPause5hThreshold.value = typeof extra?.auto_pause_5h_threshold === 'number' ? extra.auto_pause_5h_threshold * 100 : null
autoPause7dThreshold.value = typeof extra?.auto_pause_7d_threshold === 'number' ? extra.auto_pause_7d_threshold * 100 : null
autoPause5hDisabled.value = extra?.auto_pause_5h_disabled === true
@@ -6242,6 +6259,7 @@ const handleSubmit = async () => {
newExtra.web_search_emulation = webSearchEmulationMode.value
}
}
+ applyOpenAIImageSizeTiersToExtra(newExtra, openAIImageSizeTiers.value)
if (autoPause5hThreshold.value != null && autoPause5hThreshold.value > 0) {
newExtra.auto_pause_5h_threshold = autoPause5hThreshold.value / 100
} else {
diff --git a/frontend/src/components/account/OpenAIImageSizeTiersField.vue b/frontend/src/components/account/OpenAIImageSizeTiersField.vue
new file mode 100644
index 0000000000..bfc8008496
--- /dev/null
+++ b/frontend/src/components/account/OpenAIImageSizeTiersField.vue
@@ -0,0 +1,52 @@
+
+
+
+
+
{{ t('admin.accounts.openai.imageSizeTiers') }}
+
+
+
+ {{ tier }}
+
+
+
{{ t('admin.accounts.openai.imageSizeTiersDesc') }}
+
+
diff --git a/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts b/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts
index daae21b9f9..dd23419db2 100644
--- a/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts
+++ b/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts
@@ -492,6 +492,42 @@ describe('BulkEditAccountModal', () => {
})
})
+ it('生图尺寸档位独立启用,全选时提交空列表表示不限', async () => {
+ const restricted = mountModal({
+ selectedPlatforms: ['openai'],
+ selectedTypes: ['oauth', 'apikey']
+ })
+ await restricted.get('#bulk-edit-openai-image-size-tiers-enabled').setValue(true)
+ await restricted.get('[data-testid="bulk-edit-openai-image-size-tier-4K"]').setValue(false)
+ await restricted.get('#bulk-edit-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(adminAPI.accounts.bulkUpdate).toHaveBeenLastCalledWith([1, 2], {
+ extra: { openai_image_size_tiers: ['1K', '2K'] }
+ })
+ restricted.unmount()
+
+ vi.mocked(adminAPI.accounts.bulkUpdate).mockClear()
+ const unrestricted = mountModal({
+ selectedPlatforms: ['openai'],
+ selectedTypes: ['apikey']
+ })
+ await unrestricted.get('#bulk-edit-openai-image-size-tiers-enabled').setValue(true)
+ await unrestricted.get('#bulk-edit-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(adminAPI.accounts.bulkUpdate).toHaveBeenCalledWith([1, 2], {
+ extra: { openai_image_size_tiers: [] }
+ })
+ unrestricted.unmount()
+
+ const mixed = mountModal({
+ selectedPlatforms: ['openai', 'anthropic'],
+ selectedTypes: ['apikey']
+ })
+ expect(mixed.find('#bulk-edit-openai-image-size-tiers-enabled').exists()).toBe(false)
+ })
+
it('端点能力默认值提交 null,表示恢复两个默认端点', async () => {
const wrapper = mountModal({
selectedPlatforms: ['openai'],
diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
index 84cfa81123..302c78829c 100644
--- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
+++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
@@ -338,6 +338,25 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
expect(createAccountMock.mock.calls[0]?.[0]?.extra?.images_url_to_b64_json).toBe(true)
})
+ it('omits image size tiers by default and sends restricted tiers when set', async () => {
+ await submitApiKeyAccount('openai')
+ expect(createAccountMock.mock.calls[0]?.[0]?.extra).not.toHaveProperty('openai_image_size_tiers')
+
+ createAccountMock.mockClear()
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'OpenAI')
+ await selectButtonByText(wrapper, 'API Key')
+ await wrapper.get('form#create-account-form input[type="text"]').setValue('openai account')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
+ await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false)
+ await wrapper.get('[data-testid="openai-image-size-tier-2K"]').setValue(false)
+ await wrapper.get('form#create-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(createAccountMock).toHaveBeenCalledTimes(1)
+ expect(createAccountMock.mock.calls[0]?.[0]?.extra?.openai_image_size_tiers).toEqual(['4K'])
+ })
+
it('persists upstream model metadata after creating an account from preview', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenAI')
diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
index 9e786042f2..3e65714d5e 100644
--- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
+++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
@@ -1040,6 +1040,41 @@ describe('EditAccountModal', () => {
expect(updateAccountMock.mock.calls[0]?.[1]?.extra).not.toHaveProperty('images_url_to_b64_json')
})
+ it('writes restricted image size tiers into extra', async () => {
+ const account = buildAccount()
+ updateAccountMock.mockReset()
+ checkMixedChannelRiskMock.mockReset()
+ checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
+ updateAccountMock.mockResolvedValue(account)
+
+ const wrapper = mountModal(account)
+ await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false)
+ await wrapper.get('[data-testid="openai-image-size-tier-2K"]').setValue(false)
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.extra?.openai_image_size_tiers).toEqual(['4K'])
+ })
+
+ it('removes image size tiers from extra when every tier is selected again', async () => {
+ const account = buildAccount()
+ account.extra = { openai_image_size_tiers: ['1K', '2K'] }
+ updateAccountMock.mockReset()
+ checkMixedChannelRiskMock.mockReset()
+ checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
+ updateAccountMock.mockResolvedValue(account)
+
+ const wrapper = mountModal(account)
+ const tier4K = wrapper.get('[data-testid="openai-image-size-tier-4K"]')
+ expect((tier4K.element as HTMLInputElement).checked).toBe(false)
+ await tier4K.setValue(true)
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.extra).toBeDefined()
+ expect(updateAccountMock.mock.calls[0]?.[1]?.extra).not.toHaveProperty('openai_image_size_tiers')
+ })
+
it('hides the Codex namespace flatten toggle for non-OAuth OpenAI accounts', async () => {
const account = buildAccount()
const wrapper = mountModal(account)
diff --git a/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts b/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts
new file mode 100644
index 0000000000..f01cb67af7
--- /dev/null
+++ b/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it, vi } from 'vitest'
+import { mount } from '@vue/test-utils'
+import OpenAIImageSizeTiersField from '../OpenAIImageSizeTiersField.vue'
+import {
+ applyOpenAIImageSizeTiersToExtra,
+ openAIImageSizeTiersPayload,
+ readOpenAIImageSizeTiers
+} from '../openaiImageSizeTiers'
+
+vi.mock('vue-i18n', async () => {
+ const actual = await vi.importActual('vue-i18n')
+ return {
+ ...actual,
+ useI18n: () => ({ t: (key: string) => key })
+ }
+})
+
+describe('openaiImageSizeTiers helpers', () => {
+ it('reads unrestricted extra as all tiers', () => {
+ expect(readOpenAIImageSizeTiers(undefined)).toEqual(['1K', '2K', '4K'])
+ expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: [] })).toEqual(['1K', '2K', '4K'])
+ expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: ['8K'] })).toEqual(['1K', '2K', '4K'])
+ })
+
+ it('reads restricted tiers in canonical order', () => {
+ expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: ['4k', ' 1K'] })).toEqual(['1K', '4K'])
+ })
+
+ it('omits the key when every tier is allowed', () => {
+ expect(openAIImageSizeTiersPayload(['4K', '1K', '2K'])).toBeNull()
+ expect(openAIImageSizeTiersPayload(['2K', '1K'])).toEqual(['1K', '2K'])
+
+ const extra: Record = { openai_image_size_tiers: ['4K'] }
+ applyOpenAIImageSizeTiersToExtra(extra, ['1K', '2K', '4K'])
+ expect(extra).not.toHaveProperty('openai_image_size_tiers')
+ applyOpenAIImageSizeTiersToExtra(extra, ['4K'])
+ expect(extra.openai_image_size_tiers).toEqual(['4K'])
+ })
+})
+
+describe('OpenAIImageSizeTiersField', () => {
+ it('toggles tiers and keeps at least one selected', async () => {
+ const wrapper = mount(OpenAIImageSizeTiersField, {
+ props: {
+ modelValue: ['1K', '2K', '4K'],
+ 'onUpdate:modelValue': (value: string[]) => wrapper.setProps({ modelValue: value as never })
+ }
+ })
+
+ await wrapper.get('[data-testid="openai-image-size-tier-4K"]').setValue(false)
+ expect(wrapper.props('modelValue')).toEqual(['1K', '2K'])
+ await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false)
+ expect(wrapper.props('modelValue')).toEqual(['2K'])
+
+ const last = wrapper.get('[data-testid="openai-image-size-tier-2K"]')
+ await last.setValue(false)
+ expect((last.element as HTMLInputElement).checked).toBe(true)
+ expect(wrapper.props('modelValue')).toEqual(['2K'])
+
+ await wrapper.get('[data-testid="openai-image-size-tier-4K"]').setValue(true)
+ expect(wrapper.props('modelValue')).toEqual(['2K', '4K'])
+ })
+})
diff --git a/frontend/src/components/account/openaiImageSizeTiers.ts b/frontend/src/components/account/openaiImageSizeTiers.ts
new file mode 100644
index 0000000000..6cd003c57a
--- /dev/null
+++ b/frontend/src/components/account/openaiImageSizeTiers.ts
@@ -0,0 +1,37 @@
+export const OPENAI_IMAGE_SIZE_TIERS = ['1K', '2K', '4K'] as const
+
+export type OpenAIImageSizeTier = (typeof OPENAI_IMAGE_SIZE_TIERS)[number]
+
+export const OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY = 'openai_image_size_tiers'
+
+// 返回账号允许的档位(按 1K/2K/4K 排序);未配置、空列表或无有效档位视为三档全允许。
+export function readOpenAIImageSizeTiers(extra: unknown): OpenAIImageSizeTier[] {
+ const raw = (extra as Record | null | undefined)?.[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY]
+ const values = Array.isArray(raw)
+ ? raw.filter((item): item is string => typeof item === 'string').map(item => item.trim().toUpperCase())
+ : []
+ const tiers = OPENAI_IMAGE_SIZE_TIERS.filter(tier => values.includes(tier))
+ return tiers.length > 0 ? tiers : [...OPENAI_IMAGE_SIZE_TIERS]
+}
+
+export function normalizeOpenAIImageSizeTiers(tiers: readonly string[]): OpenAIImageSizeTier[] {
+ return OPENAI_IMAGE_SIZE_TIERS.filter(tier => tiers.includes(tier))
+}
+
+// 三档全选即不限:返回 null,表示 extra 中不写该键(批量编辑以空列表清除)。
+export function openAIImageSizeTiersPayload(tiers: readonly string[]): OpenAIImageSizeTier[] | null {
+ const normalized = normalizeOpenAIImageSizeTiers(tiers)
+ if (normalized.length === 0 || normalized.length === OPENAI_IMAGE_SIZE_TIERS.length) {
+ return null
+ }
+ return normalized
+}
+
+export function applyOpenAIImageSizeTiersToExtra(extra: Record, tiers: readonly string[]): void {
+ const payload = openAIImageSizeTiersPayload(tiers)
+ if (payload) {
+ extra[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] = payload
+ } else {
+ delete extra[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY]
+ }
+}
diff --git a/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue
index bc256fc479..799ce6bfc0 100644
--- a/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue
+++ b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue
@@ -21,6 +21,7 @@
{{ item.description || t('adminAccessKeys.noDescription') }} · {{ t('adminAccessKeys.expires', { value: item.expires_at || t('adminAccessKeys.never') }) }}
{{ t('adminAccessKeys.lastUsed', { value: item.last_used_at || t('adminAccessKeys.neverUsed') }) }} {{ item.last_used_ip }}
+
{{ t('adminAccessKeys.fullAccessLabel') }}
{{ t('adminAccessKeys.summary', { globals: item.policy.global_permissions.length, rules: item.policy.rules.length }) }}
{{ t('adminAccessKeys.ruleLine', { index: index + 1, summary: ruleSummary(rule) }) }}
@@ -41,6 +42,12 @@
{{ t('adminAccessKeys.expiration') }}
{{ t('adminAccessKeys.allowedIps') }}
{{ t('adminAccessKeys.enabled') }}
+
+
{{ t('adminAccessKeys.fullAccessLabel') }}
+
{{ t('adminAccessKeys.fullAccessWarning') }}
+
{{ t('adminAccessKeys.rulesSuspended') }}
+
+
{{ t('adminAccessKeys.ruleLegend', { index: index + 1 }) }}
{{ t('adminAccessKeys.allGroups') }}
@@ -48,11 +55,11 @@
{{ t('adminAccessKeys.includeUngrouped') }}
{{ t('adminAccessKeys.platforms') }}{{ platform.label }}
-
+
{{ t('adminAccessKeys.groupOperations') }}
{{ t('adminAccessKeys.modelAllowlistHint') }}
-
{{ permission.label }} {{ permission.id }}
+
{{ permissionLabel(permission) }} {{ permission.id }}
{{ t('adminAccessKeys.removeRule') }}
@@ -61,26 +68,38 @@
{{ t('adminAccessKeys.globalPermissions') }}
{{ category.name }}
- {{ permission.label }} {{ permission.id }}
+ {{ permissionLabel(permission) }} {{ permission.id }}
- {{ busy ? t('adminAccessKeys.processing') : t('adminAccessKeys.save') }} {{ t('adminAccessKeys.cancel') }}
+
+ {{ busy ? t('adminAccessKeys.processing') : t('adminAccessKeys.save') }} {{ t('adminAccessKeys.cancel') }}
+
+ {{ t('adminAccessKeys.fullAccessWarning') }}
+ {{ t('adminAccessKeys.fullAccessPhraseHint', { phrase: t('adminAccessKeys.fullAccessPhrase') }) }}
+
+ {{ t('adminAccessKeys.cancel') }}
+ {{ t('adminAccessKeys.fullAccessConfirmTitle') }}
+
+
diff --git a/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.i18n.spec.ts b/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.i18n.spec.ts
new file mode 100644
index 0000000000..4cb2a337b2
--- /dev/null
+++ b/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.i18n.spec.ts
@@ -0,0 +1,129 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createI18n } from 'vue-i18n'
+import AdminAccessKeysSettings from '../AdminAccessKeysSettings.vue'
+import en from '@/i18n/locales/en'
+import zh from '@/i18n/locales/zh'
+import enKeys from '@/i18n/locales/en/adminAccessKeys'
+import zhKeys from '@/i18n/locales/zh/adminAccessKeys'
+
+const catalogSource = readFileSync(resolve(process.cwd(), '../backend/internal/pkg/adminaccess/catalog.go'), 'utf8')
+const catalog = [...catalogSource.matchAll(/Permission\{"([^"]+)", "([^"]+)", "([^"]+)", "([^"]+)"\}/g)].map(([, id, label, category, scope]) => ({ id, label, category, scope }))
+const mocks = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn(), rotate: vi.fn(), revoke: vi.fn(), deleteRecord: vi.fn() }))
+vi.mock('@/api/admin/adminAccessKeys', () => mocks)
+vi.mock('@/api/admin/groups', () => ({ getAllIncludingInactive: vi.fn().mockResolvedValue([{ id: 7, name: 'Example group' }]) }))
+vi.mock('@/components/auth/TotpStepUpDialog.vue', () => ({ default: { template: '
' } }))
+vi.mock('@/composables/useStepUp', () => ({ useStepUp: () => ({ run: (fn: () => unknown) => fn() }), isStepUpCancelled: () => false }))
+const wrappers: ReturnType
[] = []
+afterEach(() => wrappers.splice(0).forEach(wrapper => wrapper.unmount()))
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.list.mockResolvedValue({ items: [], permissions: [...catalog, { id: 'future.feature', label: '后端新增权限', category: '后端新增分类', scope: 'global' }, { id: 'payment.mark.paid', label: '不可误认成人工确认到账', category: '未知分类', scope: 'global' }] })
+ mocks.create.mockResolvedValue({ key: 'secret', item: { id: 'created', name: 'Example key' } })
+})
+function setup(locale: 'en' | 'zh' = 'en') {
+ const i18n = createI18n({ legacy: false, locale, fallbackLocale: 'en', messages: { en, zh } })
+ const wrapper = mount(AdminAccessKeysSettings, { global: { plugins: [i18n], stubs: { teleport: true } } })
+ wrappers.push(wrapper)
+ return { wrapper, i18n }
+}
+
+describe('管理员密钥英文体验', () => {
+ it('各自后端目录的每个权限都有准确的中英文标签与分类', () => {
+ expect(catalog.length).toBeGreaterThan(50)
+ expect(new Set(catalog.map(permission => permission.id)).size).toBe(catalog.length)
+ const expectedKeys = catalog.map(permission => permission.id.replaceAll('_', '_u').replaceAll('.', '_d')).sort()
+ for (const messages of [enKeys, zhKeys]) {
+ expect(Object.keys(messages.permissions).sort()).toEqual(expectedKeys)
+ for (const { label, category } of Object.values(messages.permissions)) {
+ expect(label.trim()).not.toBe('')
+ expect(category.trim()).not.toBe('')
+ }
+ }
+ expect(en.adminAccessKeys).toEqual(enKeys)
+ expect(zh.adminAccessKeys).toEqual(zhKeys)
+ for (const permission of catalog) {
+ const key = permission.id.replaceAll('_', '_u').replaceAll('.', '_d') as keyof typeof zhKeys.permissions
+ expect(zhKeys.permissions[key]).toEqual({ label: permission.label, category: permission.category })
+ expect(enKeys.permissions[key].label).not.toMatch(/[\u3400-\u9fff]/u)
+ expect(enKeys.permissions[key].category).not.toMatch(/[\u3400-\u9fff]/u)
+ }
+ })
+
+ it('切换语言清除待确认文字和本次扩权,必须使用当前语言重新确认', async () => {
+ const { wrapper, i18n } = setup('zh')
+ await flushPromises()
+ await wrapper.get('[data-test="create"]').trigger('click')
+ await wrapper.get('[data-test="name"]').setValue('Example key')
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
+ i18n.global.locale.value = 'en'
+ await flushPromises()
+ expect(wrapper.find('[data-test="full-access-phrase"]').exists()).toBe(false)
+ expect(wrapper.get('[data-test="full-access"]').element.checked).toBe(false)
+ expect(wrapper.text()).not.toMatch(/[\u3400-\u9fff]/u)
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ expect(wrapper.get('[data-test="full-access-phrase"]').element.value).toBe('')
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('ENABLE FULL ACCESS')
+ await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
+ expect(wrapper.get('[data-test="full-access"]').element.checked).toBe(true)
+ i18n.global.locale.value = 'zh'
+ await flushPromises()
+ expect(wrapper.get('[data-test="full-access"]').element.checked).toBe(false)
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('ENABLE FULL ACCESS')
+ expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
+ await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
+ await wrapper.get('[data-test="save"]').trigger('click')
+ await flushPromises()
+ expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ policy: expect.objectContaining({ full_access: true }), confirm_full_access: true }))
+ })
+
+ it('语言切换保留已有全权权限并翻译列表摘要', async () => {
+ mocks.list.mockResolvedValueOnce({ items: [{ id: 'existing', name: 'Existing key', enabled: true, allowed_ips: [], policy: { full_access: true, rules: [{ permissions: ['accounts.read'], group_ids: [7], account_types: ['oauth'], platforms: ['openai'] }], global_permissions: [] } }], permissions: catalog })
+ const { wrapper, i18n } = setup('zh')
+ await flushPromises()
+ await wrapper.findAll('button').find(button => button.text() === '编辑权限')!.trigger('click')
+ i18n.global.locale.value = 'en'
+ await flushPromises()
+ expect(wrapper.get('[data-test="full-access"]').element.checked).toBe(true)
+ expect(wrapper.text()).toContain('Full access')
+ expect(wrapper.text()).toContain('Example group')
+ expect(wrapper.text()).not.toMatch(/[\u3400-\u9fff]/u)
+ })
+
+ it('英文环境翻译页面及后端权限目录,未知权限不泄漏中文标签或分类', async () => {
+ const { wrapper } = setup()
+ await flushPromises()
+ await wrapper.get('[data-test="create"]').trigger('click')
+ expect(wrapper.text()).toContain('Admin access keys')
+ expect(wrapper.text()).not.toMatch(/[\u3400-\u9fff]/u)
+ expect(wrapper.text()).toContain('Read accounts (redacted)')
+ expect(wrapper.text()).toContain('Finance')
+ expect(wrapper.text()).toContain('future.feature')
+ const unknown = wrapper.get('input[value="payment.mark.paid"]').element.closest('label')!
+ expect(unknown.textContent).toContain('Unknown permission (payment.mark.paid)')
+ for (const permission of catalog) {
+ const key = permission.id.replaceAll('_', '_u').replaceAll('.', '_d') as keyof typeof enKeys.permissions
+ expect(wrapper.get(`input[value="${permission.id}"]`).element.closest('label')!.textContent).toContain(enKeys.permissions[key].label)
+ }
+ const creation = wrapper.find('input[value="accounts.create"]')
+ await creation.setValue(true)
+ expect(wrapper.text()).not.toMatch(/[\u3400-\u9fff]/u)
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ expect(wrapper.text()).toContain('ENABLE FULL ACCESS')
+ expect(wrapper.text()).not.toMatch(/[\u3400-\u9fff]/u)
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
+ expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('ENABLE FULL ACCESS')
+ await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
+ await wrapper.get('[data-test="name"]').setValue('Example key')
+ await wrapper.get('[data-test="save"]').trigger('click')
+ await flushPromises()
+ expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ confirm_full_access: true, policy: expect.objectContaining({ full_access: true }) }))
+ expect(wrapper.get('[role="status"]').text()).toBe('Key saved')
+ })
+})
diff --git a/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.spec.ts b/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.spec.ts
index 42565e517a..0cc2c010af 100644
--- a/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.spec.ts
+++ b/frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.spec.ts
@@ -3,14 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import AdminAccessKeysSettings from '../AdminAccessKeysSettings.vue'
import zh from '@/i18n/locales/zh/adminAccessKeys'
import en from '@/i18n/locales/en/adminAccessKeys'
-const mountSettings = () => mount(AdminAccessKeysSettings)
-vi.mock('vue-i18n', () => ({ useI18n: () => ({
- t: (key: string, values: Record = {}) => {
- const message = zh[key.replace('adminAccessKeys.', '') as keyof typeof zh]
- if (!message) throw new Error(`缺少翻译:${key}`)
- return message.replace(/\{(\w+)\}/g, (_, name: string) => String(values[name]))
- }
-}) }))
+import { createI18n } from 'vue-i18n'
+const mountSettings = () => mount(AdminAccessKeysSettings, { global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { adminAccessKeys: zh }, en: { adminAccessKeys: en } } })], stubs: { teleport: true } } })
import { getAllIncludingInactive } from '@/api/admin/groups'
const mocks = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn(), rotate: vi.fn(), revoke: vi.fn(), deleteRecord: vi.fn(), stepUp: vi.fn((fn: () => unknown) => fn()) }))
vi.mock('@/api/admin/adminAccessKeys', () => mocks)
@@ -184,7 +178,7 @@ describe('管理员受限密钥配置', () => {
expect(wrapper.text()).not.toContain('kiro')
await wrapper.get('[data-test="save"]').trigger('click')
await flushPromises()
- expect(mocks.update).toHaveBeenCalledWith('key-2', expect.objectContaining({ name: '新名称', allowed_ips: [], policy: { rules, global_permissions: [] } }))
+ expect(mocks.update).toHaveBeenCalledWith('key-2', expect.objectContaining({ name: '新名称', allowed_ips: [], policy: { rules, global_permissions: [], full_access: false } }))
})
it('空数组返回 null 时仍可创建默认无权限密钥', async () => {
mocks.list.mockResolvedValueOnce({ items: null, permissions: null })
@@ -245,3 +239,78 @@ describe('管理员受限密钥配置', () => {
})
})
+
+describe('全权兼容模式', () => {
+ it('默认关闭,取消不会授权,输入确认文字后才允许保存全权', async () => {
+ mocks.create.mockResolvedValue({ key: 'once', item: { id: '1' } })
+ const wrapper = mountSettings()
+ await flushPromises()
+ await wrapper.get('[data-test="create"]').trigger('click')
+ await wrapper.get('[data-test="name"]').setValue('兼容工具')
+ const toggle = wrapper.get('[data-test="full-access"]')
+ expect(toggle.element.checked).toBe(false)
+ await toggle.setValue(true)
+ expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
+ await wrapper.get('[data-test="full-access-cancel"]').trigger('click')
+ expect(toggle.element.checked).toBe(false)
+ await toggle.setValue(true)
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
+ await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
+ expect(wrapper.text()).toContain('资源规则已暂停')
+ await wrapper.get('[data-test="save"]').trigger('click')
+ await flushPromises()
+ expect(mocks.create.mock.calls[0]![0]).toMatchObject({ policy: { full_access: true }, confirm_full_access: true })
+ })
+
+ it('关闭后保留原规则,并清除确认状态', async () => {
+ const item = { id: 'key-1', name: '兼容', enabled: true, allowed_ips: [], policy: { full_access: true, rules: [{ permissions: ['accounts.read'], group_ids: [7], account_types: ['oauth'], platforms: ['openai'] }], global_permissions: [] } }
+ mocks.list.mockResolvedValueOnce({ items: [item], permissions: [] })
+ mocks.update.mockResolvedValueOnce(item)
+ const wrapper = mountSettings()
+ await flushPromises()
+ expect(wrapper.text()).toContain('全权访问')
+ await wrapper.findAll('button').find(b => b.text() === '编辑权限')!.trigger('click')
+ const toggle = wrapper.get('[data-test="full-access"]')
+ expect(toggle.element.checked).toBe(true)
+ await toggle.setValue(false)
+ await wrapper.get('[data-test="save"]').trigger('click')
+ await flushPromises()
+ const input = mocks.update.mock.calls[0]![1]
+ expect(input.policy.full_access).toBe(false)
+ expect(input.policy.rules[0].permissions).toEqual(['accounts.read'])
+ expect(input.confirm_full_access).not.toBe(true)
+ })
+})
+
+describe('全权确认失败与重复开启', () => {
+ it('取消确认仍可保存受限配置,不能借确认弹窗直接保存', async () => {
+ mocks.create.mockResolvedValue({ key: 'once', item: { id: '1' } })
+ const wrapper = mountSettings()
+ await flushPromises()
+ await wrapper.get('[data-test="create"]').trigger('click')
+ await wrapper.get('[data-test="name"]').setValue('受限工具')
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ expect(wrapper.get('[data-test="save"]').attributes('disabled')).toBeDefined()
+ await wrapper.get('[data-test="save"]').trigger('click')
+ expect(mocks.create).not.toHaveBeenCalled()
+ await wrapper.get('[data-test="full-access-cancel"]').trigger('click')
+ await wrapper.get('[data-test="save"]').trigger('click')
+ await flushPromises()
+ expect(mocks.create.mock.calls[0]![0].policy.full_access).not.toBe(true)
+ expect(mocks.create.mock.calls[0]![0].confirm_full_access).toBe(false)
+ })
+
+ it('关闭后再次开启需要重新输入确认文字', async () => {
+ const wrapper = mountSettings()
+ await flushPromises()
+ await wrapper.get('[data-test="create"]').trigger('click')
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
+ await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
+ expect(wrapper.get('input[value="accounts.read"]').element.closest('fieldset[disabled]')).not.toBeNull()
+ await wrapper.get('[data-test="full-access"]').setValue(false)
+ await wrapper.get('[data-test="full-access"]').setValue(true)
+ expect(wrapper.get('[data-test="full-access-phrase"]').element.value).toBe('')
+ expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
+ })
+})
diff --git a/frontend/src/components/admin/settings/__tests__/RegistrationEmailBlacklistEditor.spec.ts b/frontend/src/components/admin/settings/__tests__/RegistrationEmailBlacklistEditor.spec.ts
new file mode 100644
index 0000000000..e0ae43eba9
--- /dev/null
+++ b/frontend/src/components/admin/settings/__tests__/RegistrationEmailBlacklistEditor.spec.ts
@@ -0,0 +1,245 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import RegistrationEmailBlacklistEditor from '../RegistrationEmailBlacklistEditor.vue'
+
+const mocks = vi.hoisted(() => ({
+ getBlacklist: vi.fn(),
+ updateBlacklist: vi.fn(),
+ findUsers: vi.fn(),
+ batchDisable: vi.fn(),
+ showSuccess: vi.fn(),
+ showError: vi.fn(),
+ showInfo: vi.fn()
+}))
+
+vi.mock('@/api', () => ({
+ adminAPI: {
+ settings: {
+ getRegistrationEmailBlacklist: mocks.getBlacklist,
+ updateRegistrationEmailBlacklist: mocks.updateBlacklist
+ },
+ users: {
+ findBlacklistedEmailUsers: mocks.findUsers,
+ batchDisable: mocks.batchDisable
+ }
+ }
+}))
+
+vi.mock('vue-i18n', () => ({
+ useI18n: () => ({
+ t: (key: string, params?: Record) =>
+ params ? `${key}:${JSON.stringify(params)}` : key,
+ locale: { value: 'en' }
+ })
+}))
+
+vi.mock('@/stores', () => ({
+ useAppStore: () => ({
+ showSuccess: mocks.showSuccess,
+ showError: mocks.showError,
+ showInfo: mocks.showInfo
+ })
+}))
+
+const wrappers: ReturnType[] = []
+
+function mountEditor() {
+ const wrapper = mount(RegistrationEmailBlacklistEditor, {
+ attachTo: document.body,
+ global: {
+ stubs: { teleport: true }
+ }
+ })
+ wrappers.push(wrapper)
+ return wrapper
+}
+
+afterEach(() => wrappers.splice(0).forEach((wrapper) => wrapper.unmount()))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.getBlacklist.mockResolvedValue({ emails: ['old@gmail.com'], max: 20000 })
+ mocks.findUsers.mockResolvedValue({ items: [], total: 0 })
+ mocks.batchDisable.mockResolvedValue({ affected: 0 })
+})
+
+describe('RegistrationEmailBlacklistEditor', () => {
+ it('批量添加后保存整份名单,并对新增项命中的用户弹窗确认禁用', async () => {
+ mocks.updateBlacklist.mockResolvedValue({
+ emails: ['new.one@gmail.com', 'new2@googlemail.com', 'old@gmail.com'],
+ added: ['new.one@gmail.com', 'new2@googlemail.com'],
+ max: 20000
+ })
+ mocks.findUsers.mockResolvedValue({
+ items: [{ id: 11, email: 'newone@gmail.com', username: 'n1' }],
+ total: 1
+ })
+ mocks.batchDisable.mockResolvedValue({ affected: 1 })
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ expect(wrapper.get('[data-testid="email-blacklist-summary"]').text()).toContain('"count":"1"')
+
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-bulk-input"]').setValue(
+ 'New.One@gmail.com, new2@googlemail.com\nold@gmail.com\nnew.one@gmail.com\nnot-an-email'
+ )
+ await wrapper.get('[data-testid="email-blacklist-bulk-add"]').trigger('click')
+
+ expect(wrapper.get('[data-testid="email-blacklist-add-result"]').text()).toContain('"added":"2","duplicates":"2"')
+ expect(wrapper.get('[data-testid="email-blacklist-invalid"]').text()).toContain('not-an-email')
+ expect(wrapper.findAll('[data-testid="email-blacklist-row"]')).toHaveLength(3)
+ expect(
+ (wrapper.get('[data-testid="email-blacklist-bulk-input"]').element as HTMLTextAreaElement).value
+ ).toBe('not-an-email')
+
+ await wrapper.get('[data-testid="email-blacklist-save"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.updateBlacklist).toHaveBeenCalledWith(['new.one@gmail.com', 'new2@googlemail.com', 'old@gmail.com'])
+ expect(mocks.findUsers).toHaveBeenCalledWith(['new.one@gmail.com', 'new2@googlemail.com'])
+ expect(wrapper.get('[data-testid="email-blacklist-matched-users"]').text()).toContain('newone@gmail.com')
+
+ await wrapper.get('[data-testid="email-blacklist-disable-confirm"]').trigger('click')
+ await flushPromises()
+ expect(mocks.batchDisable).toHaveBeenCalledWith([11])
+ expect(mocks.showSuccess).toHaveBeenLastCalledWith(
+ 'admin.settings.registration.emailBlacklist.disabled:{"count":"1"}'
+ )
+ expect(wrapper.find('[data-testid="email-blacklist-matched-users"]').exists()).toBe(false)
+ })
+
+ it('保存后没有新增项时不查询用户,没有命中时也不弹窗', async () => {
+ mocks.updateBlacklist.mockResolvedValue({ emails: [], added: [], max: 20000 })
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-clear"]').trigger('click')
+ expect(wrapper.get('[data-testid="email-blacklist-pending"]').text()).toContain('"removed":"1"')
+
+ await wrapper.get('[data-testid="email-blacklist-save"]').trigger('click')
+ await flushPromises()
+ expect(mocks.updateBlacklist).toHaveBeenCalledWith([])
+ expect(mocks.findUsers).not.toHaveBeenCalled()
+ expect(mocks.showInfo).not.toHaveBeenCalled()
+ })
+
+ it('手动检查已注册用户覆盖整份已保存名单,无命中时提示', async () => {
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-check"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.findUsers).toHaveBeenCalledWith(['old@gmail.com'])
+ expect(mocks.showInfo).toHaveBeenCalledWith('admin.settings.registration.emailBlacklist.noActiveMatches')
+ expect(wrapper.find('[data-testid="email-blacklist-matched-users"]').exists()).toBe(false)
+ })
+
+ it('未改动时保存按钮不可用,保存失败时保留弹窗并提示错误', async () => {
+ mocks.updateBlacklist.mockRejectedValue({ message: 'invalid email address (1): broken' })
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ expect(wrapper.get('[data-testid="email-blacklist-save"]').attributes('disabled')).toBeDefined()
+
+ await wrapper.get('[data-testid="email-blacklist-bulk-input"]').setValue('fresh@gmail.com')
+ await wrapper.get('[data-testid="email-blacklist-bulk-add"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-save"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.showError).toHaveBeenCalledWith('invalid email address (1): broken')
+ expect(wrapper.find('[data-testid="email-blacklist-save"]').exists()).toBe(true)
+ expect(mocks.findUsers).not.toHaveBeenCalled()
+ })
+
+ it('有未保存改动时关闭先确认,放弃后草稿丢弃,继续编辑则保留', async () => {
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-bulk-input"]').setValue('draft@gmail.com')
+ await wrapper.get('[data-testid="email-blacklist-bulk-add"]').trigger('click')
+
+ const findButton = (label: string) => wrapper.findAll('button').find((button) => button.text() === label)
+ await findButton('common.cancel')!.trigger('click')
+ expect(wrapper.text()).toContain('admin.settings.registration.emailBlacklist.discardTitle')
+
+ await findButton('admin.settings.registration.emailBlacklist.discardCancel')!.trigger('click')
+ expect(wrapper.findAll('[data-testid="email-blacklist-row"]')).toHaveLength(2)
+
+ await findButton('common.cancel')!.trigger('click')
+ await findButton('admin.settings.registration.emailBlacklist.discardConfirm')!.trigger('click')
+ expect(wrapper.find('[data-testid="email-blacklist-bulk-input"]').exists()).toBe(false)
+ expect(mocks.updateBlacklist).not.toHaveBeenCalled()
+ })
+
+ it('保存后核查新增项期间编辑入口不可用,核查结束后可正常打开和关闭', async () => {
+ let resolveFind: (value: { items: never[]; total: number }) => void = () => {}
+ mocks.findUsers.mockReturnValue(new Promise((resolve) => { resolveFind = resolve }))
+ mocks.updateBlacklist.mockResolvedValue({ emails: ['x@gmail.com', 'old@gmail.com'], added: ['x@gmail.com'], max: 20000 })
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-bulk-input"]').setValue('x@gmail.com')
+ await wrapper.get('[data-testid="email-blacklist-bulk-add"]').trigger('click')
+ await wrapper.get('[data-testid="email-blacklist-save"]').trigger('click')
+ await flushPromises()
+
+ expect(wrapper.get('[data-testid="email-blacklist-edit"]').attributes('disabled')).toBeDefined()
+ resolveFind({ items: [], total: 0 })
+ await flushPromises()
+ expect(wrapper.get('[data-testid="email-blacklist-edit"]').attributes('disabled')).toBeUndefined()
+
+ await wrapper.get('[data-testid="email-blacklist-edit"]').trigger('click')
+ const cancel = wrapper.findAll('button').find((button) => button.text() === 'common.cancel')!
+ expect(cancel.attributes('disabled')).toBeUndefined()
+ await cancel.trigger('click')
+ expect(wrapper.find('[data-testid="email-blacklist-bulk-input"]').exists()).toBe(false)
+ })
+
+ it('命中用户超过单批上限时分批禁用并汇总人数', async () => {
+ const users = Array.from({ length: 1001 }, (_, i) => ({ id: i + 1, email: `u${i}@gmail.com`, username: '' }))
+ mocks.findUsers.mockResolvedValue({ items: users, total: users.length })
+ mocks.batchDisable.mockImplementation(async (ids: number[]) => ({ affected: ids.length }))
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-check"]').trigger('click')
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-disable-confirm"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.batchDisable).toHaveBeenCalledTimes(2)
+ expect(mocks.batchDisable.mock.calls[0]![0]).toHaveLength(1000)
+ expect(mocks.batchDisable.mock.calls[1]![0]).toEqual([1001])
+ expect(mocks.showSuccess).toHaveBeenLastCalledWith(
+ 'admin.settings.registration.emailBlacklist.disabled:{"count":"1,001"}'
+ )
+ })
+
+ it('分批禁用中途失败时只保留未提交的用户,重试从断点继续', async () => {
+ const users = Array.from({ length: 1500 }, (_, i) => ({ id: i + 1, email: `u${i}@gmail.com`, username: '' }))
+ mocks.findUsers.mockResolvedValue({ items: users, total: users.length })
+ mocks.batchDisable
+ .mockResolvedValueOnce({ affected: 1000 })
+ .mockRejectedValueOnce({ message: 'timeout' })
+ .mockResolvedValueOnce({ affected: 500 })
+
+ const wrapper = mountEditor()
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-check"]').trigger('click')
+ await flushPromises()
+ await wrapper.get('[data-testid="email-blacklist-disable-confirm"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.showError).toHaveBeenCalledWith('timeout')
+ expect(wrapper.findAll('[data-testid="email-blacklist-matched-users"] li')).toHaveLength(500)
+
+ await wrapper.get('[data-testid="email-blacklist-disable-confirm"]').trigger('click')
+ await flushPromises()
+ expect(mocks.batchDisable.mock.calls[2]![0]).toEqual(users.slice(1000).map((user) => user.id))
+ expect(wrapper.find('[data-testid="email-blacklist-matched-users"]').exists()).toBe(false)
+ })
+})
diff --git a/frontend/src/composables/useAdminAccessKeyPermissions.ts b/frontend/src/composables/useAdminAccessKeyPermissions.ts
new file mode 100644
index 0000000000..aff8256d1a
--- /dev/null
+++ b/frontend/src/composables/useAdminAccessKeyPermissions.ts
@@ -0,0 +1,16 @@
+import { useI18n } from 'vue-i18n'
+import type { Permission } from '@/api/admin/adminAccessKeys'
+
+// 权限 ID 是稳定协议;后端标签和分类可能始终是中文,不作为本地化回退值。
+export function useAdminAccessKeyPermissions() {
+ const { t, te } = useI18n()
+ function permissionLabel(permission: Permission): string {
+ const key = `adminAccessKeys.permissions.${permission.id.replace(/_/g, '_u').replace(/\./g, '_d')}.label`
+ return te(key) ? t(key) : t('adminAccessKeys.unknownPermission', { id: permission.id })
+ }
+ function permissionCategory(permission: Permission): string {
+ const key = `adminAccessKeys.permissions.${permission.id.replace(/_/g, '_u').replace(/\./g, '_d')}.category`
+ return te(key) ? t(key) : t('adminAccessKeys.other')
+ }
+ return { permissionLabel, permissionCategory }
+}
diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts
index 36ebff4bee..4795be4a11 100644
--- a/frontend/src/i18n/locales/en/admin/accounts.ts
+++ b/frontend/src/i18n/locales/en/admin/accounts.ts
@@ -687,6 +687,10 @@ export default {
imagesUrlToB64Json: 'Image result URL to base64',
imagesUrlToB64JsonDesc:
'Only applies to non-streaming Images responses of OpenAI API Key accounts. When an upstream image item has a url but no b64_json, the gateway downloads the url and fills b64_json with its base64 content (url is kept) for clients built on the official API; the response is returned unchanged if the download fails.',
+ imageSizeTiers: 'Image size tiers',
+ imageSizeTiersDesc:
+ 'Limits the image size tiers this account serves, using the billing tiers: longest edge ≤1024 is 1K, ≤2048 is 2K, larger is 4K (2560x1440 is 4K). Requests with an explicit size are only scheduled to accounts allowing that tier; requests without a size or with auto prefer accounts without a tier limit, then accounts allowing 4K, 2K and 1K in that order. Selecting all tiers means no limit. Applies to the Images API and the Responses image generation tool.',
+ imageSizeTiersAtLeastOne: 'Keep at least one tier',
endpointCapabilities: 'Endpoint capabilities',
endpointCapabilitiesDesc:
'Used by account routing. The text endpoint follows the Responses API support setting above and is shown as Responses, Chat Completions, or auto mode; Embeddings independently controls /v1/embeddings.',
diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts
index c056f3925b..689e06433c 100644
--- a/frontend/src/i18n/locales/en/admin/settings.ts
+++ b/frontend/src/i18n/locales/en/admin/settings.ts
@@ -163,6 +163,43 @@ export default {
emailDomainQuota: 'Non-allowlist Domain Quota',
emailDomainQuotaHint:
'When enabled and the allowlist is not empty, every other registrable domain can register one account. When disabled, non-allowlist domains are rejected. Has no effect while the allowlist is empty',
+ emailBlacklist: {
+ title: 'Email Blacklist (Exact Match)',
+ hint: 'Listed addresses cannot register or be bound as an account email. Matching is per inbox: dots in Gmail addresses, the googlemail.com domain and +suffixes are treated as the same address. Existing accounts are not affected; use Check Registered Users to find and disable them. The list is saved from its own dialog, independent of the Save button at the bottom of this page.',
+ count: '{count} addresses',
+ loadFailed: 'Failed to load the blacklist',
+ retry: 'Retry',
+ edit: 'Edit List',
+ checkUsers: 'Check Registered Users',
+ editorTitle: 'Edit Email Blacklist',
+ bulkLabel: 'Bulk Add',
+ bulkPlaceholder: 'One address per line; commas, spaces or semicolons also work',
+ bulkAdd: 'Add to List',
+ addResult: 'Added {added}, skipped {duplicates} duplicates',
+ invalidResult: '{count} invalid entries were left in the input: {sample}',
+ listLabel: 'List ({count})',
+ pending: 'Unsaved: {added} added, {removed} removed',
+ searchPlaceholder: 'Search addresses',
+ clear: 'Clear',
+ empty: 'The list is empty',
+ noMatch: 'No matching addresses',
+ truncated: '{total} matches; showing the first {limit}. Narrow it down with search.',
+ newTag: 'Unsaved',
+ remove: 'Remove',
+ save: 'Save List',
+ saved: 'Blacklist saved with {count} addresses',
+ tooMany: 'The list can hold at most {max} addresses',
+ disableTitle: 'Disable blacklisted users?',
+ disableMessage: 'The emails of the {count} registered users below are blacklisted (including alias variants of the same inbox). Disabled users cannot sign in and their API keys stop working immediately. Disable them?',
+ disableConfirm: 'Disable {count} users',
+ disableLater: 'Not Now',
+ disabled: 'Disabled {count} users',
+ noActiveMatches: 'No active registered users match the list',
+ discardTitle: 'Discard unsaved changes?',
+ discardMessage: '{added} additions and {removed} removals have not been saved and will be lost.',
+ discardConfirm: 'Discard',
+ discardCancel: 'Keep Editing',
+ },
promoCode: 'Promo Code',
promoCodeHint: 'Allow users to use promo codes during registration',
invitationCode: 'Invitation Code Registration',
diff --git a/frontend/src/i18n/locales/en/adminAccessKeys.ts b/frontend/src/i18n/locales/en/adminAccessKeys.ts
index 4fcbc0165a..7809ec15d7 100644
--- a/frontend/src/i18n/locales/en/adminAccessKeys.ts
+++ b/frontend/src/i18n/locales/en/adminAccessKeys.ts
@@ -5,7 +5,7 @@ export default {
"secretWarning": "The full key is shown only once. Copy and save it before closing.",
"copySecret": "Copy key",
"dismissSecret": "Saved, close",
- "create": "Create scoped key",
+ "create": "Create administrator key",
"refresh": "Refresh",
"loading": "Loading keys and permissions…",
"noDescription": "No description",
@@ -31,7 +31,7 @@ export default {
"accountTypes": "Account types (account operations only; none means no account access)",
"platforms": "Platforms (multiple selection; empty allows all)",
"accountOperations": "Allowed account operations",
- "groupOperations": "Allowed group model operations (subject to the group and platform scopes above)",
+ "groupOperations": "Allowed group operations (restricted by the groups and platforms above)",
"modelAllowlistHint": "The group model allowlist restricts which models the group can use.",
"removeRule": "Remove rule",
"addRule": "Add resource rule",
@@ -69,5 +69,255 @@ export default {
"rotateConfirm": "Rotating “{name}” immediately invalidates its current key. Continue?",
"revokeConfirm": "Permanently revoking “{name}” cannot be undone. Continue?",
"deleteConfirm": "Delete the key record “{name}”? This removes it from the list only. Historical operation records are retained.",
- "legacy": "Legacy full-access key (migration to scoped keys recommended)"
+ "legacy": "Legacy full-access key (migration to scoped keys recommended)",
+ "fullAccessLabel": "Full access (legacy administrator key compatibility)",
+ "fullAccessWarning": "This key can access all administrative resources, read sensitive data, and change account and financial settings, including future administrative endpoints. Group, platform, account type, and operation rules no longer restrict this key. Endpoints requiring an administrator browser session or step-up verification keep those requirements.",
+ "rulesSuspended": "Resource rules are suspended and resume when full access is disabled. Expiration, IP restrictions, rate limits, and auditing remain active.",
+ "fullAccessConfirmTitle": "Confirm full access",
+ "fullAccessPhrase": "ENABLE FULL ACCESS",
+ "fullAccessPhraseHint": "Type “{phrase}” to confirm:",
+ "unknownPermission": "Unknown permission ({id})",
+ "permissions": {
+ "accounts_didentity_dread": {
+ "label": "Read account email, plan, and creation time (no tokens)",
+ "category": "Accounts"
+ },
+ "accounts_dusage_dread": {
+ "label": "Read and refresh authorized account quota and snapshots",
+ "category": "Accounts"
+ },
+ "accounts_dstats_dread": {
+ "label": "Read account usage and cost statistics",
+ "category": "Accounts"
+ },
+ "openai_dquota_dread": {
+ "label": "Read OpenAI upstream quota and remaining resets",
+ "category": "OpenAI"
+ },
+ "openai_dquota_dreset": {
+ "label": "Use an OpenAI reset to restore quota",
+ "category": "OpenAI"
+ },
+ "openai_dreferrals_dread": {
+ "label": "Read OpenAI referral eligibility and remaining invitations",
+ "category": "OpenAI"
+ },
+ "openai_dreferrals_dinvite": {
+ "label": "Send OpenAI invitation emails",
+ "category": "OpenAI"
+ },
+ "accounts_doptions_dwrite": {
+ "label": "Write OpenAI OAuth identity and connection options",
+ "category": "Accounts"
+ },
+ "accounts_drate_dwrite": {
+ "label": "Set account billing multiplier",
+ "category": "Accounts"
+ },
+ "groups_dlist_dread": {
+ "label": "Read selected group details (name, platform, and status)",
+ "category": "Groups"
+ },
+ "groups_dcapacity_dread": {
+ "label": "Read selected group capacity (entire group, regardless of account type)",
+ "category": "Groups"
+ },
+ "openai_dtokens_drefresh": {
+ "label": "Refresh caller-provided OpenAI tokens (returns tokens; selected proxy allowed)",
+ "category": "OAuth"
+ },
+ "accounts_dread": {
+ "label": "Read accounts (redacted)",
+ "category": "Accounts"
+ },
+ "accounts_dcreate": {
+ "label": "Create accounts",
+ "category": "Accounts"
+ },
+ "accounts_dupdate": {
+ "label": "Edit account names and notes",
+ "category": "Accounts"
+ },
+ "accounts_dcredentials": {
+ "label": "Write credentials (no read access)",
+ "category": "Accounts"
+ },
+ "accounts_dmodels_dwrite": {
+ "label": "Edit account model allowlist IDs and mappings",
+ "category": "Accounts"
+ },
+ "accounts_dnetwork": {
+ "label": "Change endpoints, proxies, and connection options",
+ "category": "Accounts"
+ },
+ "accounts_dstatus": {
+ "label": "Enable, disable, and toggle account scheduling",
+ "category": "Accounts"
+ },
+ "accounts_dschedule": {
+ "label": "Change concurrency, priority, and expiration",
+ "category": "Accounts"
+ },
+ "accounts_drefresh": {
+ "label": "Refresh OAuth credentials",
+ "category": "Accounts"
+ },
+ "accounts_drecover": {
+ "label": "Clear account errors and rate-limit state",
+ "category": "Accounts"
+ },
+ "accounts_ddelete": {
+ "label": "Delete accounts (affects shared groups)",
+ "category": "Accounts"
+ },
+ "accounts_dgroups": {
+ "label": "Change authorized group associations",
+ "category": "Accounts"
+ },
+ "groups_dmodels_dread": {
+ "label": "Read selected group model allowlists and candidate IDs",
+ "category": "Group models"
+ },
+ "groups_dmodels_dwrite": {
+ "label": "Edit selected group model allowlists (affects the entire group)",
+ "category": "Group models"
+ },
+ "proxies_dread": {
+ "label": "Read proxy IP candidates (paginated, without credentials)",
+ "category": "Proxies"
+ },
+ "models_ddefaults_dread": {
+ "label": "Read default model allowlist IDs and mappings",
+ "category": "Models"
+ },
+ "dashboard_dread": {
+ "label": "Read site-wide business reports",
+ "category": "Reports"
+ },
+ "users_dread": {
+ "label": "Read all user profiles (including contact details)",
+ "category": "Users"
+ },
+ "users_dbalance_dread": {
+ "label": "Read all user balances and transaction history",
+ "category": "Finance"
+ },
+ "users_dbalance_dwrite": {
+ "label": "Add or subtract any user balance",
+ "category": "Finance"
+ },
+ "users_dquotas_dread": {
+ "label": "Read all user platform quotas",
+ "category": "Users"
+ },
+ "users_dquotas_dwrite": {
+ "label": "Change and reset all user platform quotas",
+ "category": "Users"
+ },
+ "groups_dread": {
+ "label": "Read all group configurations",
+ "category": "Groups"
+ },
+ "usage_dread": {
+ "label": "Read site-wide usage details and user usage",
+ "category": "Reports"
+ },
+ "payment_dread": {
+ "label": "Read all payment orders and reports",
+ "category": "Finance"
+ },
+ "payment_dcancel": {
+ "label": "Cancel payment orders",
+ "category": "Finance"
+ },
+ "payment_dfulfill": {
+ "label": "Retry payment order fulfillment",
+ "category": "Finance"
+ },
+ "payment_drefund": {
+ "label": "Issue refunds and confirm refund results",
+ "category": "Finance"
+ },
+ "payment_dplans_dread": {
+ "label": "Read all payment plans",
+ "category": "Finance"
+ },
+ "payment_dplans_dwrite": {
+ "label": "Create, edit, and delete payment plans",
+ "category": "Finance"
+ },
+ "subscriptions_dread": {
+ "label": "Read all subscription records",
+ "category": "Subscriptions"
+ },
+ "subscriptions_dassign": {
+ "label": "Assign subscriptions to any user",
+ "category": "Subscriptions"
+ },
+ "subscriptions_dextend": {
+ "label": "Extend subscription expiration",
+ "category": "Subscriptions"
+ },
+ "subscriptions_drevoke": {
+ "label": "Revoke subscriptions",
+ "category": "Subscriptions"
+ },
+ "subscriptions_drestore": {
+ "label": "Restore subscriptions",
+ "category": "Subscriptions"
+ },
+ "subscriptions_dreset": {
+ "label": "Reset subscription quota",
+ "category": "Subscriptions"
+ },
+ "announcements_dread": {
+ "label": "Read all announcements and read receipts",
+ "category": "Content"
+ },
+ "announcements_dwrite": {
+ "label": "Create, publish, and edit announcements",
+ "category": "Content"
+ },
+ "announcements_ddelete": {
+ "label": "Delete announcements",
+ "category": "Content"
+ },
+ "promo_dread": {
+ "label": "Read promotion codes and usage records",
+ "category": "Finance"
+ },
+ "promo_dwrite": {
+ "label": "Create and edit promotion code benefits",
+ "category": "Finance"
+ },
+ "promo_ddelete": {
+ "label": "Delete promotion codes",
+ "category": "Finance"
+ },
+ "ops_dread": {
+ "label": "Read site-wide operational metrics",
+ "category": "Monitoring"
+ },
+ "ops_derrors_dread": {
+ "label": "Read site-wide request error details (sensitive)",
+ "category": "Monitoring"
+ },
+ "ops_derrors_dresolve": {
+ "label": "Mark request error resolution status",
+ "category": "Monitoring"
+ },
+ "ops_dalerts_dread": {
+ "label": "Read site-wide alert rules and events",
+ "category": "Monitoring"
+ },
+ "ops_dalerts_dwrite": {
+ "label": "Change alert rules, status, and silences",
+ "category": "Monitoring"
+ },
+ "system_dread": {
+ "label": "Read current and available system versions",
+ "category": "System"
+ }
+ },
+ "listSeparator": ", "
}
diff --git a/frontend/src/i18n/locales/en/common.ts b/frontend/src/i18n/locales/en/common.ts
index 694dbb74ff..856bd5ba5f 100644
--- a/frontend/src/i18n/locales/en/common.ts
+++ b/frontend/src/i18n/locales/en/common.ts
@@ -248,6 +248,7 @@ export default {
loginFailed: 'Login failed. Please check your credentials and try again.',
errors: {
USER_NOT_ACTIVE: 'Account has been disabled.',
+ EMAIL_BLOCKED: 'This email address is not allowed. Please use a different one.',
},
registrationFailed: 'Registration failed. Please try again.',
emailDomainRegistrationLimit:
diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts
index d43bed531c..d06cda2797 100644
--- a/frontend/src/i18n/locales/en/dashboard.ts
+++ b/frontend/src/i18n/locales/en/dashboard.ts
@@ -454,6 +454,7 @@ export default {
noDataToExport: 'No data to export',
exportSuccess: 'Usage data exported successfully',
exportFailed: 'Failed to export usage data',
+ exportRateLimited: 'Too many requests, export will resume in {seconds} seconds',
exportExcelSuccess: 'Usage data exported successfully (Excel format)',
exportExcelFailed: 'Failed to export usage data',
imageUnit: ' images',
diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts
index d34e534ef7..a6ff6363ab 100644
--- a/frontend/src/i18n/locales/zh/admin/accounts.ts
+++ b/frontend/src/i18n/locales/zh/admin/accounts.ts
@@ -799,6 +799,10 @@ export default {
imagesUrlToB64Json: '生图结果 URL 转 base64',
imagesUrlToB64JsonDesc:
'仅对 OpenAI API Key 的 Images 非流式响应生效。上游返回的图片缺少 b64_json 但带 url 时,网关下载该 url 并以 base64 回填 b64_json(url 保留),兼容按官方接口实现的客户端;下载失败则原样返回。',
+ imageSizeTiers: '生图尺寸档位',
+ imageSizeTiersDesc:
+ '限制本账号承接的生图尺寸档位,档位与计费一致:最长边 ≤1024 为 1K,≤2048 为 2K,更大为 4K(2560x1440 属于 4K)。指定了尺寸的请求只会调度到允许该档位的账号;未传尺寸或 auto 的请求优先调度到不限档位的账号,没有时依次选允许 4K、2K、1K 的账号。全选即不限,对 Images 接口与 Responses 生图工具生效。',
+ imageSizeTiersAtLeastOne: '至少保留一个档位',
endpointCapabilities: '端点能力',
endpointCapabilitiesDesc:
'用于调度筛选。文本端点会跟随上方 Responses API 支持显示为 Responses、Chat Completions 或自动模式;Embeddings 独立控制 /v1/embeddings。',
diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts
index 27b282b88d..f48160dbe6 100644
--- a/frontend/src/i18n/locales/zh/admin/settings.ts
+++ b/frontend/src/i18n/locales/zh/admin/settings.ts
@@ -163,6 +163,43 @@ export default {
emailDomainQuota: '非白名单域名限量注册',
emailDomainQuotaHint:
'开启后,白名单非空时,其他可注册主域名各限注册一个账户;关闭时非白名单域名直接拒绝注册。白名单为空时本开关无效果',
+ emailBlacklist: {
+ title: '邮箱黑名单(精确匹配)',
+ hint: '禁止名单中的邮箱注册,或绑定为账号邮箱。按收件箱匹配:Gmail 地址里的点号、googlemail.com 域名,以及各邮箱的 + 后缀都视为同一邮箱。已注册的账号不受影响,可用「检查已注册用户」找出后禁用。名单在弹窗里单独保存,不受页面底部保存按钮影响。',
+ count: '当前 {count} 个邮箱',
+ loadFailed: '黑名单加载失败',
+ retry: '重试',
+ edit: '编辑名单',
+ checkUsers: '检查已注册用户',
+ editorTitle: '编辑邮箱黑名单',
+ bulkLabel: '批量添加',
+ bulkPlaceholder: '每行一个邮箱,也可以用逗号、空格或分号分隔',
+ bulkAdd: '添加到列表',
+ addResult: '新增 {added} 个,跳过重复 {duplicates} 个',
+ invalidResult: '{count} 个格式无效,已留在输入框中:{sample}',
+ listLabel: '名单({count} 个)',
+ pending: '未保存:新增 {added},移除 {removed}',
+ searchPlaceholder: '搜索邮箱',
+ clear: '清空',
+ empty: '名单为空',
+ noMatch: '没有匹配的邮箱',
+ truncated: '共 {total} 条匹配,仅显示前 {limit} 条,请用搜索缩小范围',
+ newTag: '未保存',
+ remove: '移除',
+ save: '保存名单',
+ saved: '黑名单已保存,共 {count} 个邮箱',
+ tooMany: '名单最多 {max} 个邮箱',
+ disableTitle: '禁用命中黑名单的用户?',
+ disableMessage: '以下 {count} 个已注册用户的邮箱在黑名单中(含同一收件箱的别名变体)。禁用后无法登录,API Key 也会立即停用。是否禁用?',
+ disableConfirm: '禁用 {count} 个用户',
+ disableLater: '暂不禁用',
+ disabled: '已禁用 {count} 个用户',
+ noActiveMatches: '名单中没有仍在启用的已注册用户',
+ discardTitle: '放弃未保存的改动?',
+ discardMessage: '还有新增 {added} 个、移除 {removed} 个改动没有保存,关闭后会丢失。',
+ discardConfirm: '放弃改动',
+ discardCancel: '继续编辑',
+ },
promoCode: '优惠码',
promoCodeHint: '允许用户在注册时使用优惠码',
invitationCode: '邀请码注册',
diff --git a/frontend/src/i18n/locales/zh/adminAccessKeys.ts b/frontend/src/i18n/locales/zh/adminAccessKeys.ts
index 415e457437..21c9779b07 100644
--- a/frontend/src/i18n/locales/zh/adminAccessKeys.ts
+++ b/frontend/src/i18n/locales/zh/adminAccessKeys.ts
@@ -5,7 +5,7 @@ export default {
"secretWarning": "完整密钥仅展示本次,请立即复制保存。关闭后无法再次查看。",
"copySecret": "复制密钥",
"dismissSecret": "已保存,关闭展示",
- "create": "创建受限密钥",
+ "create": "创建管理密钥",
"refresh": "刷新列表",
"loading": "正在加载密钥及权限目录…",
"noDescription": "无备注",
@@ -31,7 +31,7 @@ export default {
"accountTypes": "账户类型(仅限制账户操作,未选表示无账户权限)",
"platforms": "平台(可多选,未选表示不限平台)",
"accountOperations": "允许的账户操作",
- "groupOperations": "允许的分组模型操作(同样受上方分组与平台限制)",
+ "groupOperations": "允许的分组操作(受上方分组与平台限制)",
"modelAllowlistHint": "分组模型白名单会限制分组可调用的模型。",
"removeRule": "删除规则",
"addRule": "添加资源规则",
@@ -69,5 +69,255 @@ export default {
"rotateConfirm": "轮换“{name}”将立即使原密钥失效,是否继续?",
"revokeConfirm": "永久撤销“{name}”后无法恢复,是否继续?",
"deleteConfirm": "确定删除“{name}”的密钥记录?删除只是从列表移除,历史操作记录仍会继续保留。",
- "legacy": "旧版全权密钥兼容区(建议迁移到受限密钥)"
+ "legacy": "旧版全权密钥兼容区(建议迁移到受限密钥)",
+ "fullAccessLabel": "全权访问(兼容旧版管理员 Key)",
+ "fullAccessWarning": "开启后,此密钥可访问全部管理资源、读取敏感数据并修改账户和财务配置;未来新增的管理接口也将允许访问。分组、平台、账户类型和操作规则不再限制此密钥。仅限管理员登录会话及二次验证的接口仍遵循原要求。",
+ "rulesSuspended": "资源规则已暂停,关闭全权访问后恢复;有效期、IP 限制、限流和审计继续生效。",
+ "fullAccessConfirmTitle": "确认开启全权访问",
+ "fullAccessPhrase": "开启全权访问",
+ "fullAccessPhraseHint": "请输入“{phrase}”以确认:",
+ "unknownPermission": "未知权限({id})",
+ "permissions": {
+ "accounts_didentity_dread": {
+ "label": "读取账户邮箱、套餐及创建时间(不含令牌)",
+ "category": "账户"
+ },
+ "accounts_dusage_dread": {
+ "label": "读取及主动刷新授权账户额度与快照",
+ "category": "账户"
+ },
+ "accounts_dstats_dread": {
+ "label": "读取账户用量与费用统计",
+ "category": "账户"
+ },
+ "openai_dquota_dread": {
+ "label": "查询 OpenAI 上游额度与重置次数",
+ "category": "OpenAI"
+ },
+ "openai_dquota_dreset": {
+ "label": "消耗 OpenAI 重置次数恢复额度",
+ "category": "OpenAI"
+ },
+ "openai_dreferrals_dread": {
+ "label": "查询 OpenAI 邀请资格与次数",
+ "category": "OpenAI"
+ },
+ "openai_dreferrals_dinvite": {
+ "label": "发送 OpenAI 邀请邮件",
+ "category": "OpenAI"
+ },
+ "accounts_doptions_dwrite": {
+ "label": "写入 OpenAI OAuth 身份与连接选项",
+ "category": "账户"
+ },
+ "accounts_drate_dwrite": {
+ "label": "设置账户计费倍率",
+ "category": "账户"
+ },
+ "groups_dlist_dread": {
+ "label": "读取所选分组基本信息(名称、平台、状态)",
+ "category": "分组"
+ },
+ "groups_dcapacity_dread": {
+ "label": "读取所选分组容量(整个分组,不按账户类型过滤)",
+ "category": "分组"
+ },
+ "openai_dtokens_drefresh": {
+ "label": "刷新调用方提供的 OpenAI 令牌(返回令牌,可使用所选代理)",
+ "category": "OAuth"
+ },
+ "accounts_dread": {
+ "label": "查看账户(脱敏)",
+ "category": "账户"
+ },
+ "accounts_dcreate": {
+ "label": "创建账户",
+ "category": "账户"
+ },
+ "accounts_dupdate": {
+ "label": "编辑名称与备注",
+ "category": "账户"
+ },
+ "accounts_dcredentials": {
+ "label": "写入凭证(不包含读取)",
+ "category": "账户"
+ },
+ "accounts_dmodels_dwrite": {
+ "label": "编辑账户白名单模型 ID 与映射",
+ "category": "账户"
+ },
+ "accounts_dnetwork": {
+ "label": "修改接入地址、代理与连接选项",
+ "category": "账户"
+ },
+ "accounts_dstatus": {
+ "label": "启用、停用与调度开关",
+ "category": "账户"
+ },
+ "accounts_dschedule": {
+ "label": "修改并发、优先级与有效期",
+ "category": "账户"
+ },
+ "accounts_drefresh": {
+ "label": "刷新 OAuth 凭证",
+ "category": "账户"
+ },
+ "accounts_drecover": {
+ "label": "清除账户错误与限流状态",
+ "category": "账户"
+ },
+ "accounts_ddelete": {
+ "label": "删除账户(影响共享分组)",
+ "category": "账户"
+ },
+ "accounts_dgroups": {
+ "label": "调整授权分组关联",
+ "category": "账户"
+ },
+ "groups_dmodels_dread": {
+ "label": "读取所选分组模型白名单与候选 ID",
+ "category": "分组模型"
+ },
+ "groups_dmodels_dwrite": {
+ "label": "编辑所选分组模型白名单(影响整个分组)",
+ "category": "分组模型"
+ },
+ "proxies_dread": {
+ "label": "读取代理 IP 候选(分页,不含认证凭证)",
+ "category": "代理"
+ },
+ "models_ddefaults_dread": {
+ "label": "读取默认白名单模型 ID(含默认映射)",
+ "category": "模型"
+ },
+ "dashboard_dread": {
+ "label": "读取全站经营报表",
+ "category": "报表"
+ },
+ "users_dread": {
+ "label": "读取全站用户资料(含联系方式)",
+ "category": "用户"
+ },
+ "users_dbalance_dread": {
+ "label": "读取全站用户余额及流水",
+ "category": "财务"
+ },
+ "users_dbalance_dwrite": {
+ "label": "增减任意用户余额",
+ "category": "财务"
+ },
+ "users_dquotas_dread": {
+ "label": "读取全站用户平台额度",
+ "category": "用户"
+ },
+ "users_dquotas_dwrite": {
+ "label": "修改与重置全站用户平台额度",
+ "category": "用户"
+ },
+ "groups_dread": {
+ "label": "读取所有分组配置",
+ "category": "分组"
+ },
+ "usage_dread": {
+ "label": "读取全站用量明细及用户用量",
+ "category": "报表"
+ },
+ "payment_dread": {
+ "label": "读取全站支付订单与报表",
+ "category": "财务"
+ },
+ "payment_dcancel": {
+ "label": "取消支付订单",
+ "category": "财务"
+ },
+ "payment_dfulfill": {
+ "label": "重新履约支付订单",
+ "category": "财务"
+ },
+ "payment_drefund": {
+ "label": "发起退款及确认退款结果",
+ "category": "财务"
+ },
+ "payment_dplans_dread": {
+ "label": "读取全部支付套餐",
+ "category": "财务"
+ },
+ "payment_dplans_dwrite": {
+ "label": "创建、修改和删除支付套餐",
+ "category": "财务"
+ },
+ "subscriptions_dread": {
+ "label": "读取全站订阅记录",
+ "category": "订阅"
+ },
+ "subscriptions_dassign": {
+ "label": "分配全站用户订阅",
+ "category": "订阅"
+ },
+ "subscriptions_dextend": {
+ "label": "延长订阅有效期",
+ "category": "订阅"
+ },
+ "subscriptions_drevoke": {
+ "label": "撤销订阅",
+ "category": "订阅"
+ },
+ "subscriptions_drestore": {
+ "label": "恢复订阅",
+ "category": "订阅"
+ },
+ "subscriptions_dreset": {
+ "label": "重置订阅额度",
+ "category": "订阅"
+ },
+ "announcements_dread": {
+ "label": "读取所有公告与阅读记录",
+ "category": "内容"
+ },
+ "announcements_dwrite": {
+ "label": "创建、发布与修改公告",
+ "category": "内容"
+ },
+ "announcements_ddelete": {
+ "label": "删除公告",
+ "category": "内容"
+ },
+ "promo_dread": {
+ "label": "读取优惠码及使用记录",
+ "category": "财务"
+ },
+ "promo_dwrite": {
+ "label": "创建与修改优惠码权益",
+ "category": "财务"
+ },
+ "promo_ddelete": {
+ "label": "删除优惠码",
+ "category": "财务"
+ },
+ "ops_dread": {
+ "label": "读取全站运维指标",
+ "category": "监控"
+ },
+ "ops_derrors_dread": {
+ "label": "读取全站请求错误详情(敏感)",
+ "category": "监控"
+ },
+ "ops_derrors_dresolve": {
+ "label": "标记请求错误处理状态",
+ "category": "监控"
+ },
+ "ops_dalerts_dread": {
+ "label": "读取全站告警规则与事件",
+ "category": "监控"
+ },
+ "ops_dalerts_dwrite": {
+ "label": "修改告警规则、状态与静默",
+ "category": "监控"
+ },
+ "system_dread": {
+ "label": "读取系统版本与可更新版本",
+ "category": "系统"
+ }
+ },
+ "listSeparator": "、"
}
diff --git a/frontend/src/i18n/locales/zh/common.ts b/frontend/src/i18n/locales/zh/common.ts
index d2377249d0..83556f9e1d 100644
--- a/frontend/src/i18n/locales/zh/common.ts
+++ b/frontend/src/i18n/locales/zh/common.ts
@@ -248,6 +248,7 @@ export default {
loginFailed: '登录失败,请检查您的凭据后重试。',
errors: {
USER_NOT_ACTIVE: '账号已被禁用',
+ EMAIL_BLOCKED: '该邮箱不允许注册,请更换其他邮箱。',
},
registrationFailed: '注册失败,请重试。',
emailDomainRegistrationLimit:
diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts
index 15c276d6e6..4ca5a30cae 100644
--- a/frontend/src/i18n/locales/zh/dashboard.ts
+++ b/frontend/src/i18n/locales/zh/dashboard.ts
@@ -459,6 +459,7 @@ export default {
noDataToExport: '没有可导出的数据',
exportSuccess: '使用数据导出成功',
exportFailed: '使用数据导出失败',
+ exportRateLimited: '请求过于频繁,{seconds} 秒后自动继续导出',
exportExcelSuccess: '使用数据导出成功(Excel格式)',
exportExcelFailed: '使用数据导出失败',
imageUnit: '张',
diff --git a/frontend/src/utils/__tests__/registrationEmailBlacklist.spec.ts b/frontend/src/utils/__tests__/registrationEmailBlacklist.spec.ts
new file mode 100644
index 0000000000..12deea0547
--- /dev/null
+++ b/frontend/src/utils/__tests__/registrationEmailBlacklist.spec.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+import {
+ mergeIntoBlacklist,
+ normalizeBlacklistEmail,
+ parseBlacklistInput
+} from '../registrationEmailBlacklist'
+
+describe('registrationEmailBlacklist', () => {
+ it('normalizes addresses the same way as the backend', () => {
+ expect(normalizeBlacklistEmail(' Alice@Gmail.COM ')).toBe('alice@gmail.com')
+ expect(normalizeBlacklistEmail('user@example.com.')).toBe('user@example.com')
+ expect(normalizeBlacklistEmail('a.b+tag@googlemail.com')).toBe('a.b+tag@googlemail.com')
+ expect(normalizeBlacklistEmail('@gmail.com')).toBeNull()
+ expect(normalizeBlacklistEmail('user@')).toBeNull()
+ expect(normalizeBlacklistEmail('a@b@gmail.com')).toBeNull()
+ expect(normalizeBlacklistEmail('user@localhost')).toBeNull()
+ expect(normalizeBlacklistEmail('user@bad_domain.com')).toBeNull()
+ expect(normalizeBlacklistEmail(`${'x'.repeat(65)}@gmail.com`)).toBeNull()
+ expect(normalizeBlacklistEmail('a\u0085b@gmail.com')).toBeNull()
+ expect(normalizeBlacklistEmail(`${'用'.repeat(21)}@example.com`)).toBe(`${'用'.repeat(21)}@example.com`)
+ expect(normalizeBlacklistEmail(`${'用'.repeat(22)}@example.com`)).toBeNull()
+ expect(normalizeBlacklistEmail('İvan@Example.com')).toBe('İvan@example.com')
+ })
+
+ it('splits pasted text and separates invalid tokens', () => {
+ expect(parseBlacklistInput('A@gmail.com, b@gmail.com;c@gmail.com\n\nbad a@gmail.com')).toEqual({
+ valid: ['a@gmail.com', 'b@gmail.com', 'c@gmail.com'],
+ invalid: ['bad'],
+ duplicates: 1
+ })
+ expect(parseBlacklistInput(' ')).toEqual({ valid: [], invalid: [], duplicates: 0 })
+ })
+
+ it('prepends only new addresses and counts duplicates', () => {
+ expect(mergeIntoBlacklist(['x@gmail.com'], ['y@gmail.com', 'x@gmail.com', 'z@gmail.com'])).toEqual({
+ list: ['y@gmail.com', 'z@gmail.com', 'x@gmail.com'],
+ added: ['y@gmail.com', 'z@gmail.com'],
+ duplicates: 1
+ })
+ })
+})
diff --git a/frontend/src/utils/ccswitchImport.ts b/frontend/src/utils/ccswitchImport.ts
index 1aee39d159..8314c26980 100644
--- a/frontend/src/utils/ccswitchImport.ts
+++ b/frontend/src/utils/ccswitchImport.ts
@@ -1,6 +1,6 @@
import type { GroupPlatform } from '@/types'
-export const OPENAI_CC_SWITCH_CODEX_MODEL = 'gpt-5.5'
+export const OPENAI_CC_SWITCH_CODEX_MODEL = 'gpt-5.6-sol'
export const GROK_CC_SWITCH_MODEL = 'grok-4.5'
export type CcSwitchClientType = 'claude' | 'gemini'
diff --git a/frontend/src/utils/registrationEmailBlacklist.ts b/frontend/src/utils/registrationEmailBlacklist.ts
new file mode 100644
index 0000000000..4d38c7539b
--- /dev/null
+++ b/frontend/src/utils/registrationEmailBlacklist.ts
@@ -0,0 +1,106 @@
+// Exact registration email blacklist input helpers. Validation follows the
+// backend (NormalizeRegistrationEmailBlacklistEntry): trim, drop the domain root
+// dot, local part ≤ 64 UTF-8 bytes, whole address ≤ 254 UTF-8 bytes. Only ASCII
+// letters are lowercased here; the backend applies full lowercasing on save and
+// returns the stored form.
+
+const TOKEN_SPLIT_RE = /[\s,,;;]+/
+const DOMAIN_PATTERN =
+ /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/
+const LOCAL_MAX_BYTES = 64
+const EMAIL_MAX_BYTES = 254
+const utf8 = new TextEncoder()
+
+function utf8Length(value: string): number {
+ return utf8.encode(value).length
+}
+
+function hasControlChar(value: string): boolean {
+ for (let i = 0; i < value.length; i++) {
+ const code = value.charCodeAt(i)
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
+ return true
+ }
+ }
+ return false
+}
+
+/** Returns the normalized address, or null when the token is not a valid email. */
+export function normalizeBlacklistEmail(raw: string): string | null {
+ const value = String(raw ?? '').trim().replace(/[A-Z]+/g, (letters) => letters.toLowerCase())
+ const at = value.indexOf('@')
+ if (at <= 0) {
+ return null
+ }
+ const local = value.slice(0, at)
+ const domain = value.slice(at + 1).replace(/\.+$/, '')
+ if (!domain || domain.includes('@')) {
+ return null
+ }
+ if (utf8Length(local) > LOCAL_MAX_BYTES || /\s/.test(local) || hasControlChar(local)) {
+ return null
+ }
+ if (!DOMAIN_PATTERN.test(domain)) {
+ return null
+ }
+ const email = `${local}@${domain}`
+ return utf8Length(email) > EMAIL_MAX_BYTES ? null : email
+}
+
+export interface ParsedBlacklistInput {
+ /** Normalized, de-duplicated addresses in input order. */
+ valid: string[]
+ /** Raw tokens that are not valid addresses. */
+ invalid: string[]
+ /** Tokens dropped because an earlier token normalized to the same address. */
+ duplicates: number
+}
+
+/** Splits pasted text on whitespace, commas and semicolons into addresses. */
+export function parseBlacklistInput(input: string): ParsedBlacklistInput {
+ const valid: string[] = []
+ const invalid: string[] = []
+ const seen = new Set()
+ let duplicates = 0
+ for (const token of String(input ?? '').split(TOKEN_SPLIT_RE)) {
+ if (!token) {
+ continue
+ }
+ const email = normalizeBlacklistEmail(token)
+ if (!email) {
+ invalid.push(token)
+ continue
+ }
+ if (seen.has(email)) {
+ duplicates++
+ continue
+ }
+ seen.add(email)
+ valid.push(email)
+ }
+ return { valid, invalid, duplicates }
+}
+
+export interface MergeBlacklistResult {
+ list: string[]
+ added: string[]
+ duplicates: number
+}
+
+/** Prepends addresses not already in the list; existing order is kept. */
+export function mergeIntoBlacklist(existing: string[], incoming: string[]): MergeBlacklistResult {
+ const present = new Set(existing)
+ const added: string[] = []
+ for (const email of incoming) {
+ if (present.has(email)) {
+ continue
+ }
+ present.add(email)
+ added.push(email)
+ }
+ return {
+ list: [...added, ...existing],
+ added,
+ duplicates: incoming.length - added.length
+ }
+}
diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue
index 36bbfd4b4a..a0a5149f9b 100644
--- a/frontend/src/views/admin/SettingsView.vue
+++ b/frontend/src/views/admin/SettingsView.vue
@@ -1512,6 +1512,9 @@
/>
+
+
+
({
getStreamTimeoutSettings,
getRectifierSettings,
getBetaPolicySettings,
+ getRegistrationEmailBlacklist: vi.fn().mockResolvedValue({ emails: [], max: 20000 }),
},
accounts: {
getUpstreamBillingProbeSettings,
diff --git a/frontend/src/views/auth/EmailVerifyView.vue b/frontend/src/views/auth/EmailVerifyView.vue
index 52198961e6..bed6c9268a 100644
--- a/frontend/src/views/auth/EmailVerifyView.vue
+++ b/frontend/src/views/auth/EmailVerifyView.vue
@@ -786,6 +786,9 @@ function buildRegistrationErrorMessage(error: unknown, fallback: string): string
if (extractApiErrorCode(error) === 'EMAIL_DOMAIN_REGISTRATION_LIMIT') {
return t('auth.emailDomainRegistrationLimit')
}
+ if (extractApiErrorCode(error) === 'EMAIL_BLOCKED') {
+ return t('auth.errors.EMAIL_BLOCKED')
+ }
return buildAuthErrorMessage(error, { fallback })
}
diff --git a/frontend/src/views/auth/RegisterView.vue b/frontend/src/views/auth/RegisterView.vue
index a3f9c0e4a5..99866d76e5 100644
--- a/frontend/src/views/auth/RegisterView.vue
+++ b/frontend/src/views/auth/RegisterView.vue
@@ -1112,6 +1112,9 @@ function buildRegistrationErrorMessage(error: unknown, fallback: string): string
if (extractApiErrorCode(error) === 'EMAIL_DOMAIN_REGISTRATION_LIMIT') {
return t('auth.emailDomainRegistrationLimit')
}
+ if (extractApiErrorCode(error) === 'EMAIL_BLOCKED') {
+ return t('auth.errors.EMAIL_BLOCKED')
+ }
return buildAuthErrorMessage(error, { fallback })
}
diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue
index c188248069..8ced361457 100644
--- a/frontend/src/views/user/UsageView.vue
+++ b/frontend/src/views/user/UsageView.vue
@@ -632,6 +632,27 @@ const escapeCSVValue = (value: unknown): string => {
return str
}
+const EXPORT_PAGE_SIZE = 1000
+const EXPORT_RATE_LIMIT_MAX_RETRIES = 3
+const EXPORT_RATE_LIMIT_MAX_WAIT_SECONDS = 60
+
+// 导出逐页请求计入按用户的重查询限流;429 时按 Retry-After 等待后重试同一页。
+const queryExportPage = async (params: UsageQueryParams) => {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await usageAPI.query(params)
+ } catch (error: any) {
+ if (error?.status !== 429 || attempt >= EXPORT_RATE_LIMIT_MAX_RETRIES) throw error
+ const waitSeconds = Math.min(
+ Math.max(error.retry_after_seconds ?? EXPORT_RATE_LIMIT_MAX_WAIT_SECONDS, 1),
+ EXPORT_RATE_LIMIT_MAX_WAIT_SECONDS
+ )
+ appStore.showInfo(t('usage.exportRateLimited', { seconds: waitSeconds }))
+ await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000))
+ }
+ }
+}
+
const exportToCSV = async () => {
if (pagination.total === 0) {
appStore.showWarning(t('usage.noDataToExport'))
@@ -641,11 +662,10 @@ const exportToCSV = async () => {
appStore.showInfo(t('usage.preparingExport'))
try {
const allLogs: UsageLog[] = []
- const pageSize = 100
- const exportParams = buildUsageListParams(1, pageSize)
- const totalPages = Math.ceil(pagination.total / pageSize)
+ const exportParams = buildUsageListParams(1, EXPORT_PAGE_SIZE)
+ const totalPages = Math.ceil(pagination.total / EXPORT_PAGE_SIZE)
for (let page = 1; page <= totalPages; page++) {
- const response = await usageAPI.query({ ...exportParams, page })
+ const response = await queryExportPage({ ...exportParams, page })
allLogs.push(...response.items)
}
if (allLogs.length === 0) {
diff --git a/frontend/src/views/user/__tests__/UsageView.spec.ts b/frontend/src/views/user/__tests__/UsageView.spec.ts
index 34df794bc5..2748fccf28 100644
--- a/frontend/src/views/user/__tests__/UsageView.spec.ts
+++ b/frontend/src/views/user/__tests__/UsageView.spec.ts
@@ -71,6 +71,7 @@ const messages: Record = {
'usage.preparingExport': 'Preparing export',
'usage.exportSuccess': 'Export success',
'usage.exportFailed': 'Export failed',
+ 'usage.exportRateLimited': 'Rate limited',
'common.refresh': 'Refresh',
'common.reset': 'Reset',
}
@@ -390,7 +391,7 @@ describe('user UsageView', () => {
expect(exportedBlob).not.toBeNull()
expect(query).toHaveBeenCalledWith(expect.objectContaining({
- page_size: 100,
+ page_size: 1000,
sort_by: 'created_at',
sort_order: 'desc',
native_compaction_v2: true,
@@ -450,7 +451,7 @@ describe('user UsageView', () => {
})
it('keeps the initial filters, sort, and filename while exporting multiple pages', async () => {
- const pageResponse = { items: [usageLog], total: 101, pages: 2 }
+ const pageResponse = { items: [usageLog], total: 1001, pages: 2 }
query.mockResolvedValue(pageResponse)
const wrapper = mountUsageView()
await flushPromises()
@@ -478,7 +479,7 @@ describe('user UsageView', () => {
await wrapper.findAll('button').find((button) => button.text() === 'Export CSV')!.trigger('click')
const initialParams = { ...query.mock.calls[0][0] }
expect(initialParams).toMatchObject({
- page: 1, page_size: 100, start_date: '2026-03-01', end_date: '2026-03-08',
+ page: 1, page_size: 1000, start_date: '2026-03-01', end_date: '2026-03-08',
sort_by: 'created_at', sort_order: 'desc',
})
@@ -511,6 +512,65 @@ describe('user UsageView', () => {
}
})
+ it('waits for Retry-After and retries the same page when export is rate limited', async () => {
+ const wrapper = mountUsageView()
+ await flushPromises()
+ query.mockClear()
+ query.mockRejectedValueOnce({ status: 429, code: 'RATE_LIMITED', retry_after_seconds: 2 })
+ const originalCreateObjectURL = window.URL.createObjectURL
+ const originalRevokeObjectURL = window.URL.revokeObjectURL
+ window.URL.createObjectURL = vi.fn(() => 'blob:usage-export') as typeof window.URL.createObjectURL
+ window.URL.revokeObjectURL = vi.fn(() => {}) as typeof window.URL.revokeObjectURL
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ vi.useFakeTimers()
+
+ try {
+ const exporting = (wrapper.vm as any).exportToCSV()
+ await vi.advanceTimersByTimeAsync(1999)
+ expect(query).toHaveBeenCalledTimes(1)
+ expect(showInfo).toHaveBeenCalledWith('Rate limited')
+
+ await vi.advanceTimersByTimeAsync(1)
+ await exporting
+ expect(query).toHaveBeenCalledTimes(2)
+ expect(query.mock.calls[1]).toEqual(query.mock.calls[0])
+ expect(clickSpy).toHaveBeenCalled()
+ expect(showSuccess).toHaveBeenCalledWith('Export success')
+ expect(showError).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ window.URL.createObjectURL = originalCreateObjectURL
+ window.URL.revokeObjectURL = originalRevokeObjectURL
+ clickSpy.mockRestore()
+ wrapper.unmount()
+ }
+ })
+
+ it('fails the export after repeated rate limiting', async () => {
+ const wrapper = mountUsageView()
+ await flushPromises()
+ query.mockClear()
+ query.mockRejectedValue({ status: 429, code: 'RATE_LIMITED', retry_after_seconds: 1 })
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.useFakeTimers()
+
+ try {
+ const exporting = (wrapper.vm as any).exportToCSV()
+ await vi.advanceTimersByTimeAsync(3000)
+ await exporting
+ expect(query).toHaveBeenCalledTimes(4)
+ expect(clickSpy).not.toHaveBeenCalled()
+ expect(showError).toHaveBeenCalledWith('Export failed')
+ expect((wrapper.vm as any).exporting).toBe(false)
+ } finally {
+ vi.useRealTimers()
+ vi.mocked(console.error).mockRestore()
+ clickSpy.mockRestore()
+ wrapper.unmount()
+ }
+ })
+
it('exports historical image rows with image billing mode derived from image_count', async () => {
query.mockResolvedValue({
items: [