Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

fix: revoke official model access when sessions expire

Leggett79504d85f71c
diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.ts
index 8533fd9b..fdf30cf6 100644
--- a/apps/daemon/src/gateway/account-service.ts
+++ b/apps/daemon/src/gateway/account-service.ts
@@ -118,7 +118,12 @@ export function createGatewayAccountService(input: {
credentials = { ...original, ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };
await store.writeCredentials(credentials);
} catch (error) {
- if (error instanceof GatewayError && error.status === 401) { state.authState = 'expired'; await input.closeRuntime(); }
+ if (error instanceof GatewayError && error.status === 401 && generation === expected && credentials === original && state.authState === 'signed_in') {
+ state = { ...state, authState: 'expired', activationState: 'inactive', bindingVersion: null, activationError: null };
+ runtimeTextModel = undefined; accessController?.abort();
+ clearInterval(usageTimer); usageTimer = undefined;
+ await input.closeRuntime();
+ }
throw error;
}
})();
diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.ts
index 413632e5..7ac2a87f 100644
--- a/apps/daemon/test/unit/gateway-account-service.test.ts
+++ b/apps/daemon/test/unit/gateway-account-service.test.ts
@@ -352,6 +352,29 @@ it('refreshes the official catalog when idle, preserving choices and deferring p
} finally { clock.mockRestore(); await f.service.close(); }
});
+it('revokes model readiness when account polling detects an expired session', async () => {
+ const f = await setup();
+ const server = Fastify();
+ const clock = vi.spyOn(Date, 'now');
+ const startedAt = Date.now();
+ try {
+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);
+ const ready = await f.service.readState();
+ expect(ready.activationState).toBe('ready');
+ await registerGatewayAccountRoutes(server, f.service);
+ clock.mockReturnValue(startedAt + 16 * 60_000);
+ f.client.refresh.mockRejectedValueOnce(new GatewayError('auth_required', 401));
+ const response = await server.inject({ method: 'GET', url: '/gateway/account' });
+ expect(response.statusCode).toBe(200);
+ expect(response.json()).toMatchObject({ source: 'gateway', authState: 'expired', activationState: 'inactive', bindingVersion: null,
+ models: ready.models, selectedModels: ready.selectedModels });
+ expect(f.close).toHaveBeenCalledOnce();
+ const selection = await server.inject({ method: 'PATCH', url: '/gateway/model', payload: { modality: 'text', model: 'gateway-text' } });
+ expect(selection.statusCode).toBe(401);
+ expect(selection.json().error.code).toBe('GATEWAY_AUTH_REQUIRED');
+ } finally { clock.mockRestore(); await server.close(); await f.service.close(); }
+});
+
it('clears an expired device session before starting reauthorization', async () => {
const f = await setup();
const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);
@@ -359,7 +382,7 @@ it('clears an expired device session before starting reauthorization', async ()
try {
f.client.refresh.mockRejectedValueOnce(new GatewayError('auth_required', 401));
await expect(f.service.modelCredentials()).rejects.toMatchObject({ status: 401 });
- expect((await f.service.readState()).authState).toBe('expired');
+ expect(await f.service.readState()).toMatchObject({ authState: 'expired', activationState: 'inactive' });
const next = await f.service.startAuthorization();
await f.service.pollAuthorization(next.attemptId);
expect(await f.service.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready', account: { id: '2' } });
diff --git a/apps/web/src/features/settings/OfficialServicesSettingsView.tsx b/apps/web/src/features/settings/OfficialServicesSettingsView.tsx
index 6c389444..6dfd508b 100644
--- a/apps/web/src/features/settings/OfficialServicesSettingsView.tsx
+++ b/apps/web/src/features/settings/OfficialServicesSettingsView.tsx
@@ -4,6 +4,7 @@ import type { GatewayAccountState, GatewayModel } from '@opencreator/protocol';
import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
import OfficialModelSelect from '../../components/forms/OfficialModelSelect.js';
+import { ApiClientError } from '../../runtime/errors.js';
import './official-services-settings.css';
export function OfficialServicesSettingsView(props: { state: GatewayAccountState; service: GatewayAccountSettingsService; onChange(state: GatewayAccountState): void }) {
@@ -33,12 +34,19 @@ export function OfficialServicesSettingsView(props: { state: GatewayAccountState
</span>
</span>
<span className="official-services-model-select">
- <OfficialModelSelect label={modality.label} describedBy={`official-${modality.id}-count`} models={models} disabled={pendingModality !== null || props.state.activationState !== 'ready' || models.length === 0}
+ <OfficialModelSelect label={modality.label} describedBy={`official-${modality.id}-count`} models={models} disabled={pendingModality !== null || props.state.authState !== 'signed_in' || props.state.source !== 'gateway' || props.state.activationState !== 'ready' || models.length === 0}
value={props.state.selectedModels?.[modality.id] ?? models[0]?.id ?? ''}
onChange={id => {
setPendingModality(modality.id); setError('');
void props.service.selectModel(modality.id, id).then(props.onChange)
- .catch(() => setError(l('模型切换失败,请等待当前任务结束后重试', 'Could not switch models. Wait for the current task to finish and try again.')))
+ .catch(async cause => {
+ if (cause instanceof ApiClientError && cause.code === 'GATEWAY_AUTH_REQUIRED') {
+ setError(l('登录已过期,请重新登录', 'Session expired; sign in again'));
+ await props.service.getState().then(props.onChange).catch(() => undefined);
+ } else {
+ setError(l('模型切换失败,请等待当前任务结束后重试', 'Could not switch models. Wait for the current task to finish and try again.'));
+ }
+ })
.finally(() => setPendingModality(null));
}} />
{saving ? <LoaderCircle className="official-services-spinner" size={16} aria-hidden="true" /> : null}
diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx
index e64beba2..182c72ab 100644
--- a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx
+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx
@@ -9,6 +9,7 @@ import type { GatewayAccountState } from '@opencreator/protocol';
import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';
import { createGatewayAccountService } from '../../services/gateway-account-service.js';
import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';
+import { ApiClientError } from '../../runtime/errors.js';
const runtimeStatus = {
connected: true,
@@ -48,6 +49,50 @@ describe('OpenCreatorSettingsView', () => {
await waitFor(() => expect(changed).toHaveBeenCalledWith(next));
expect(client.patch).toHaveBeenCalledWith('/gateway/model', { modality: 'text', model: 'vendor/second' });
});
+ it.each(['ready', 'inactive'] as const)('disables official models on session expiry with %s activation and recovers after sign-in', async activationState => {
+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: 'a:1',
+ models: [{ id: 'vendor/first', modality: 'text', capabilities: ['responses'] }, { id: 'vendor/second', modality: 'text', capabilities: ['responses'] }], selectedModels: { text: 'vendor/second' }, activationError: null };
+ const expired = { ...state, authState: 'expired' as const, activationState };
+ const client = { get: vi.fn(), post: vi.fn(), patch: vi.fn() };
+ const service = createGatewayAccountService(client);
+ const onOpenPersonalCenter = vi.fn();
+ const props = { runtimeStatus, gatewayAccountService: service, initialTab: 'ai-services' as const, onOpenPersonalCenter, onBack: vi.fn() };
+ const view = render(<OpenCreatorSettingsView {...props} gatewayAccountState={state}/>);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('combobox', { name: '文本模型' }));
+ expect(screen.getByRole('listbox', { name: '文本模型' })).toBeInTheDocument();
+ view.rerender(<OpenCreatorSettingsView {...props} gatewayAccountState={expired}/>);
+ expect(await screen.findByText('登录已过期')).toBeInTheDocument();
+ expect(screen.queryByText('已连接')).not.toBeInTheDocument();
+ expect(screen.getByRole('status')).not.toHaveClass('is-ready');
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ for (const model of screen.getAllByRole('combobox')) expect(model).toBeDisabled();
+ expect(screen.getByRole('combobox', { name: '文本模型' })).toHaveValue('second');
+ await user.click(screen.getByRole('button', { name: '重新登录' }));
+ expect(onOpenPersonalCenter).toHaveBeenCalledOnce();
+ expect(client.patch).not.toHaveBeenCalled();
+ view.rerender(<OpenCreatorSettingsView {...props} gatewayAccountState={state}/>);
+ expect(await screen.findByText('已连接')).toBeInTheDocument();
+ expect(screen.getByRole('combobox', { name: '文本模型' })).toBeEnabled();
+ expect(screen.getByRole('combobox', { name: '文本模型' })).toHaveValue('second');
+ });
+ it('refreshes account state when a model change discovers an expired session', async () => {
+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: 'a:1',
+ models: [{ id: 'vendor/first', modality: 'text', capabilities: ['responses'] }, { id: 'vendor/second', modality: 'text', capabilities: ['responses'] }], selectedModels: { text: 'vendor/first' }, activationError: null };
+ const expired = { ...state, authState: 'expired' as const, activationState: 'inactive' as const };
+ const client = { get: vi.fn().mockResolvedValue(expired), post: vi.fn(), patch: vi.fn().mockRejectedValue(new ApiClientError({ status: 401, code: 'GATEWAY_AUTH_REQUIRED', message: 'Sign in again' })) };
+ const service = createGatewayAccountService(client);
+ const changed = vi.fn();
+ render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={state} onGatewayStateChange={changed} initialTab="ai-services" onBack={vi.fn()}/>);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('combobox', { name: '文本模型' }));
+ await user.click(screen.getByRole('option', { name: 'second' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('登录已过期,请重新登录');
+ expect(screen.queryByText(/请等待当前任务结束/)).not.toBeInTheDocument();
+ await waitFor(() => expect(changed).toHaveBeenCalledWith(expired));
+ expect(client.get).toHaveBeenCalledWith('/gateway/account');
+ expect(screen.getByRole('combobox', { name: '文本模型' })).toBeDisabled();
+ });
it('shows custom settings for guests and directs sign-in to the personal center', async () => {
const gateway: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };
const service: GatewayAccountSettingsService = { getState: vi.fn(async () => gateway), setSource: vi.fn(), selectModel: vi.fn(), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), getOrders: vi.fn(), getOrder: vi.fn(), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn() };
diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx
index 98b3fb2b..1d14d806 100644
--- a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx
+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx
@@ -1,5 +1,5 @@
import { lazy, Suspense, useEffect, useRef, useState, type CSSProperties } from 'react';
-import { Check, CircleCheck, CircleAlert, FolderOpen, Moon, Save, Sun, UserRound } from 'lucide-react';
+import { Check, CircleCheck, CircleAlert, FolderOpen, LogIn, Moon, Save, Sun, UserRound } from 'lucide-react';
import type {
CodexProfileListResponse,
CodexStatusResponse,
@@ -121,6 +121,13 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {
const { t } = useAppLanguage();
const l = useLocalizedCopy();
const officialMode = gatewayState !== undefined && (gatewayState.source === 'gateway' || gatewayState.authState !== 'signed_out');
+ const officialConnected = gatewayState?.authState === 'signed_in' && gatewayState.source === 'gateway' && gatewayState.activationState === 'ready';
+ const officialStatus = gatewayState?.authState === 'expired' ? l('登录已过期', 'Session expired')
+ : gatewayState?.authState === 'authorizing' ? l('正在登录', 'Signing in')
+ : gatewayState?.authState === 'signing_out' ? l('正在退出登录…', 'Signing out…')
+ : gatewayState?.authState !== 'signed_in' ? l('未登录', 'Signed out')
+ : gatewayState.activationState === 'loading' ? l('正在连接', 'Connecting')
+ : officialConnected ? l('已连接', 'Connected') : l('暂不可用', 'Unavailable');
const tabs: Array<{ id: SettingsTab; label: string }> = [
{ id: 'general', label: t('settings.tab.general') },
{ id: 'ai-services', label: t('settings.tab.aiServices') },
@@ -212,12 +219,14 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {
<header className="official-services-heading">
<div>
<h1 id="official-services-title">{l('AI 服务', 'AI services')}</h1>
- <p className={`official-services-status${gatewayState.activationState === 'ready' ? ' is-ready' : ''}`} role="status">
- {gatewayState.activationState === 'ready' ? <CircleCheck size={14} aria-hidden="true" /> : <CircleAlert size={14} aria-hidden="true" />}
- {gatewayState.authState === 'authorizing' ? l('正在登录', 'Signing in') : gatewayState.activationState === 'loading' ? l('正在连接', 'Connecting') : gatewayState.activationState === 'ready' ? l('已连接', 'Connected') : gatewayState.authState === 'expired' ? l('登录已过期', 'Session expired') : l('暂不可用', 'Unavailable')}
+ <p className={`official-services-status${officialConnected ? ' is-ready' : ''}`} role="status">
+ {officialConnected ? <CircleCheck size={14} aria-hidden="true" /> : <CircleAlert size={14} aria-hidden="true" />}
+ {officialStatus}
</p>
</div>
- {props.onOpenPersonalCenter ? <button type="button" onClick={props.onOpenPersonalCenter}><UserRound size={15} aria-hidden="true"/>{l('账户', 'Account')}</button> : null}
+ {props.onOpenPersonalCenter ? <button type="button" onClick={props.onOpenPersonalCenter}>
+ {gatewayState.authState === 'expired' ? <><LogIn size={15} aria-hidden="true"/>{l('重新登录', 'Sign in again')}</> : <><UserRound size={15} aria-hidden="true"/>{l('账户', 'Account')}</>}
+ </button> : null}
</header>
{modeControls}
{props.gatewayAccountService ? <OfficialServicesSettingsView state={gatewayState} service={props.gatewayAccountService} onChange={next => { setGatewayState(next); props.onGatewayStateChange?.(next); }} /> : null}