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.

21.2 KB
Raw Blame
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';
import {
  createCreatorServicesConfigStoreWithTextModelFallback,
  createCreatorServicesConfigStore,
  createFileCreatorServicesConfigStore,
  createOpenCreatorCreatorServicesConfigStore,
  CreatorServicesConfigStoreError,
  parseCreatorServicesConfig,
  presentCreatorServicesConfig,
  retainCreatorServicesCredentials,
  type CreatorServicesConfigStore
} from '../../src/creator-services/config-store.js';

describe('CreatorServicesConfigStore', () => {
  it('migrates saved image settings and persists the replacement while retaining credentials and other models', async () => {
    const legacy = createDefaultCreatorServicesConfig();
    legacy.image.openai = { model: 'gpt-image-1', baseUrl: 'https://images.example.test/v1', apiKey: 'image-secret' };
    legacy.llm.model = 'custom-text';
    let saved = JSON.stringify(legacy);
    const store = createCreatorServicesConfigStore({
      getPassword: async () => saved,
      setPassword: async value => { saved = value; },
      deletePassword: async () => undefined
    });
    const loaded = await store.read();
    expect(loaded.image.openai).toEqual({ ...legacy.image.openai, model: 'gpt-image-2' });
    expect(loaded.llm.model).toBe('custom-text');
    expect(legacy.image.openai.model).toBe('gpt-image-1');
    await store.write(legacy);
    expect(JSON.parse(saved).image.openai.model).toBe('gpt-image-2');
    expect((await store.read()).image.openai.apiKey).toBe('image-secret');
  });

  it('migrates legacy OSS settings and retains a custom region and endpoint across reloads', async () => {
    const legacy = createDefaultCreatorServicesConfig();
    const { region: _region, endpoint: _endpoint, ...oldOss } = legacy.transcription.aliyun.oss;
    let saved: string | null = JSON.stringify({ ...legacy, transcription: {
      ...legacy.transcription, aliyun: { ...legacy.transcription.aliyun, oss: oldOss }
    } });
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => saved),
      setPassword: vi.fn(async value => { saved = value; }),
      deletePassword: vi.fn(async () => { saved = null; })
    });
    const config = await store.read();
    expect(config.transcription.aliyun.oss).toMatchObject({ region: 'cn-shanghai', endpoint: '' });
    config.transcription.aliyun.oss.region = 'ap-southeast-1';
    config.transcription.aliyun.oss.endpoint = 'https://oss-ap-southeast-1.aliyuncs.com';
    await store.write(config);
    expect((await store.read()).transcription.aliyun.oss).toEqual(config.transcription.aliyun.oss);
    config.transcription.aliyun.oss.region = '  ';
    config.transcription.aliyun.oss.endpoint = '';
    expect(parseCreatorServicesConfig(config).transcription.aliyun.oss.region).toBe('cn-shanghai');
  });

  it.each(['file:///tmp/audio', 'https://user:[email protected]', 'https://oss.example.com/bucket', 'https://oss.example.com/?token=secret', 'https://oss.example.com/#audio'])('rejects an invalid OSS service endpoint: %s', endpoint => {
    const config = createDefaultCreatorServicesConfig();
    config.transcription.aliyun.oss.endpoint = endpoint;
    expect(() => parseCreatorServicesConfig(config)).toThrow();
  });

  let root: string | undefined;

  afterEach(() => {
    if (root !== undefined) rmSync(root, { recursive: true, force: true });
    root = undefined;
    vi.unstubAllEnvs();
  });

  it('returns KrillinAI-compatible defaults when no credential is saved', async () => {
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => null),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toEqual(createDefaultCreatorServicesConfig());
  });

  it('writes and reads the full configuration through its persistence entry', async () => {
    let saved: string | null = null;
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => saved),
      setPassword: vi.fn(async value => {
        saved = value;
      }),
      deletePassword: vi.fn(async () => {
        saved = null;
      })
    });
    const config = createDefaultCreatorServicesConfig();
    config.llm.apiKey = 'sk-private';
    config.tts.provider = 'minimax';

    await expect(store.write(config)).resolves.toEqual(config);
    await expect(store.read()).resolves.toEqual(config);
    expect(saved).toContain('sk-private');
    await expect(store.reset()).resolves.toEqual(createDefaultCreatorServicesConfig());
    expect(saved).toBeNull();
  });

  it('persists all provider settings in a local JSON configuration file', async () => {
    root = mkdtempSync(join(tmpdir(), 'opencreator-creator-services-'));
    const path = join(root, 'config', 'creator-services.json');
    const store = createFileCreatorServicesConfigStore(path);
    const config = createDefaultCreatorServicesConfig();
    config.image.provider = 'gemini';
    config.image.gemini.apiKey = 'gemini-file-key';

    await store.write(config);

    await expect(store.read()).resolves.toEqual(config);
    expect(JSON.parse(readFileSync(path, 'utf8'))).toMatchObject({
      image: {
        provider: 'gemini',
        gemini: { apiKey: 'gemini-file-key' }
      }
    });
  });

  it('persists Codex native image selection without an image API credential', async () => {
    let saved: string | null = null;
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => saved),
      setPassword: vi.fn(async value => { saved = value; }),
      deletePassword: vi.fn(async () => { saved = null; })
    });
    const config = createDefaultCreatorServicesConfig();
    config.image.provider = 'codex-native';

    await expect(store.write(config)).resolves.toEqual(config);
    await expect(store.read()).resolves.toEqual(config);

    const presented = presentCreatorServicesConfig(config);
    expect(presented.config.image.provider).toBe('codex-native');
    expect(presented.config.image.codexNative).toEqual({});
    expect(presented.configuredCredentials).not.toEqual(
      expect.arrayContaining([
        'image.openai.apiKey',
        'image.jimeng.apiKey',
        'image.kling.accessKey',
        'image.kling.secretKey',
        'image.gemini.apiKey'
      ])
    );
  });

  it('stores public settings in config.toml and credentials in credentials.json', async () => {
    vi.stubEnv('VOLCENGINE_APP_ID', '');
    vi.stubEnv('VOLCENGINE_ACCESS_TOKEN', '');
    root = mkdtempSync(join(tmpdir(), 'opencreator-creator-services-'));
    const configFile = join(root, 'config.toml');
    const credentialsFile = join(root, 'credentials.json');
    const config = createDefaultCreatorServicesConfig();
    config.proxy = 'http://127.0.0.1:7897';
    config.image.provider = 'gemini';
    config.image.gemini.apiKey = 'gemini-private-key';

    const store = createOpenCreatorCreatorServicesConfigStore({
      configFile,
      credentialsFile
    });

    await expect(store.write(config)).resolves.toEqual(config);
    await expect(store.read()).resolves.toEqual(config);
    expect(readFileSync(configFile, 'utf8')).toContain('[creator_services.image]');
    expect(readFileSync(configFile, 'utf8')).not.toContain('gemini-private-key');
    expect(JSON.parse(readFileSync(credentialsFile, 'utf8'))).toMatchObject({
      creatorServices: {
        'image.gemini.apiKey': 'gemini-private-key'
      }
    });
  });

  it('fills volcengine speech credentials from environment without persisting them', async () => {
    vi.stubEnv('VOLCENGINE_APP_ID', 'env-app-id');
    vi.stubEnv('VOLCENGINE_ACCESS_TOKEN', 'env-access-token');
    root = mkdtempSync(join(tmpdir(), 'opencreator-creator-services-'));
    const configFile = join(root, 'config.toml');
    const credentialsFile = join(root, 'credentials.json');
    const store = createOpenCreatorCreatorServicesConfigStore({
      configFile,
      credentialsFile
    });

    const config = await store.read();
    expect(config.transcription.provider).toBe('volcengine');
    expect(config.transcription.volcengine.appId).toBe('env-app-id');
    expect(config.transcription.volcengine.accessToken).toBe('env-access-token');
    expect(config.tts.provider).toBe('volcengine');
    expect(config.tts.volcengine.appId).toBe('env-app-id');
    expect(config.tts.volcengine.accessToken).toBe('env-access-token');
    expect(existsSync(configFile)).toBe(false);
    expect(existsSync(credentialsFile)).toBe(false);
  });

  it('redacts and retains credentials for every image and video provider', () => {
    const current = createDefaultCreatorServicesConfig();
    current.image.openai.apiKey = 'image-openai';
    current.image.jimeng.apiKey = 'image-jimeng';
    current.image.kling.accessKey = 'image-kling-access';
    current.image.kling.secretKey = 'image-kling-secret';
    current.image.gemini.apiKey = 'image-gemini';
    current.video.seedance.apiKey = 'video-seedance';
    current.video.kling.accessKey = 'video-kling-access';
    current.video.kling.secretKey = 'video-kling-secret';
    current.video.veo.apiKey = 'video-veo';

    const presented = presentCreatorServicesConfig(current);
    expect(presented.configuredCredentials).toEqual(expect.arrayContaining([
      'image.openai.apiKey',
      'image.jimeng.apiKey',
      'image.kling.accessKey',
      'image.kling.secretKey',
      'image.gemini.apiKey',
      'video.seedance.apiKey',
      'video.kling.accessKey',
      'video.kling.secretKey',
      'video.veo.apiKey'
    ]));
    expect(presented.config.image.openai.apiKey).toBe('');
    expect(presented.config.image.jimeng.apiKey).toBe('');
    expect(presented.config.image.kling.accessKey).toBe('');
    expect(presented.config.image.kling.secretKey).toBe('');
    expect(presented.config.image.gemini.apiKey).toBe('');
    expect(presented.config.video.seedance.apiKey).toBe('');
    expect(presented.config.video.kling.accessKey).toBe('');
    expect(presented.config.video.kling.secretKey).toBe('');
    expect(presented.config.video.veo.apiKey).toBe('');

    const retained = retainCreatorServicesCredentials(presented.config, current);
    expect(retained.image).toEqual(current.image);
    expect(retained.video).toEqual(current.video);
  });

  it('redacts and retains the simplified TTS provider credentials', () => {
    const current = createDefaultCreatorServicesConfig();
    current.tts.openai.apiKey = 'tts-openai';
    current.tts.minimax.apiKey = 'tts-minimax';
    current.tts.aliyun.apiKey = 'tts-aliyun';

    const presented = presentCreatorServicesConfig(current);

    expect(presented.configuredCredentials).toEqual(expect.arrayContaining([
      'tts.openai.apiKey',
      'tts.minimax.apiKey',
      'tts.aliyun.apiKey'
    ]));
    expect(presented.config.tts.openai.apiKey).toBe('');
    expect(presented.config.tts.minimax.apiKey).toBe('');
    expect(presented.config.tts.aliyun.apiKey).toBe('');
    expect(retainCreatorServicesCredentials(presented.config, current).tts).toEqual(current.tts);
  });

  it('redacts and retains Volcengine speech credentials', () => {
    const current = createDefaultCreatorServicesConfig();
    current.transcription.volcengine.appId = 'asr-app';
    current.transcription.volcengine.accessToken = 'asr-token';
    current.tts.volcengine.appId = 'tts-app';
    current.tts.volcengine.accessToken = 'tts-token';

    const presented = presentCreatorServicesConfig(current);
    expect(presented.configuredCredentials).toEqual(expect.arrayContaining([
      'transcription.volcengine.appId',
      'transcription.volcengine.accessToken',
      'tts.volcengine.appId',
      'tts.volcengine.accessToken'
    ]));
    expect(presented.config.transcription.volcengine.appId).toBe('');
    expect(presented.config.transcription.volcengine.accessToken).toBe('');
    expect(presented.config.tts.volcengine.appId).toBe('');
    expect(presented.config.tts.volcengine.accessToken).toBe('');
    expect(retainCreatorServicesCredentials(presented.config, current).transcription.volcengine)
      .toEqual(current.transcription.volcengine);
    expect(retainCreatorServicesCredentials(presented.config, current).tts.volcengine)
      .toEqual(current.tts.volcengine);
  });

  it('clears an explicitly removed Volcengine App ID while retaining the API key', () => {
    const current = createDefaultCreatorServicesConfig();
    current.transcription.volcengine.appId = 'legacy-app-id';
    current.transcription.volcengine.accessToken = 'new-api-key';
    const presented = presentCreatorServicesConfig(current);

    // `presented.config` has every credential blanked, which is what the client
    // sends back; blank normally means "keep", so the App ID only disappears
    // when it is explicitly listed.
    const retained = retainCreatorServicesCredentials(
      presented.config,
      current,
      ['transcription.volcengine.appId']
    );

    expect(retained.transcription.volcengine.appId).toBe('');
    expect(retained.transcription.volcengine.accessToken).toBe('new-api-key');
  });

  it('redacts and retains a configured FunASR API key', () => {
    const current = createDefaultCreatorServicesConfig();
    current.transcription.funasr.apiKey = 'funasr-secret';

    const presented = presentCreatorServicesConfig(current);
    expect(presented.configuredCredentials).toContain('transcription.funasr.apiKey');
    expect(presented.config.transcription.funasr.apiKey).toBe('');
    expect(retainCreatorServicesCredentials(presented.config, current).transcription.funasr.apiKey)
      .toBe('funasr-secret');

    const changedEndpoint = structuredClone(presented.config);
    changedEndpoint.transcription.funasr.baseUrl = 'https://another-asr.example/v1';
    expect(retainCreatorServicesCredentials(changedEndpoint, current).transcription.funasr.apiKey)
      .toBe('');
  });

  it('migrates legacy tts.volcengine.apiKey into accessToken', () => {
    const current = createDefaultCreatorServicesConfig();
    const parsed = parseCreatorServicesConfig({
      ...current,
      tts: {
        ...current.tts,
        volcengine: {
          baseUrl: current.tts.volcengine.baseUrl,
          apiKey: 'legacy-token',
          model: current.tts.volcengine.model,
          defaultVoiceId: current.tts.volcengine.defaultVoiceId,
          appId: 'app-1'
        }
      }
    } as unknown);

    expect(parsed.tts.volcengine.accessToken).toBe('legacy-token');
    expect(parsed.tts.volcengine.appId).toBe('app-1');
    expect(parsed.tts.volcengine).not.toHaveProperty('apiKey');
  });

  it('uses Codex as fallback until a custom text model is configured', async () => {
    let persisted = createDefaultCreatorServicesConfig();
    const rawStore: CreatorServicesConfigStore = {
      read: vi.fn(async () => structuredClone(persisted)),
      write: vi.fn(async config => {
        persisted = structuredClone(config);
        return structuredClone(config);
      }),
      reset: vi.fn(async () => {
        persisted = createDefaultCreatorServicesConfig();
        return structuredClone(persisted);
      })
    };
    const fallback = {
      read: vi.fn(async () => ({
        baseUrl: 'https://codex.example.test/v1',
        apiKey: 'sk-codex',
        model: 'gpt-codex'
      }))
    };
    const store = createCreatorServicesConfigStoreWithTextModelFallback(rawStore, fallback);

    await expect(store.read()).resolves.toMatchObject({
      llm: {
        baseUrl: 'https://codex.example.test/v1',
        apiKey: 'sk-codex',
        model: 'gpt-codex',
        source: 'codex'
      }
    });

    const codexConfig = await store.read();
    codexConfig.proxy = 'http://127.0.0.1:7897';
    await store.write(codexConfig);
    expect(persisted.llm.apiKey).toBe('');
    expect(persisted.llm.source).toBe('codex');

    const custom = await store.read();
    custom.llm = {
      baseUrl: 'https://custom.example.test/v1',
      apiKey: 'sk-custom',
      model: 'gpt-custom',
      jsonMode: true,
      source: 'custom'
    };
    await expect(store.write(custom)).resolves.toMatchObject({
      llm: {
        baseUrl: 'https://custom.example.test/v1',
        apiKey: 'sk-custom',
        model: 'gpt-custom',
        source: 'custom'
      }
    });

    await expect(store.reset()).resolves.toMatchObject({
      llm: {
        baseUrl: 'https://codex.example.test/v1',
        apiKey: 'sk-codex',
        model: 'gpt-codex',
        source: 'codex'
      }
    });
  });

  it('adds video generation defaults when reading an older saved configuration', async () => {
    const legacy = createDefaultCreatorServicesConfig() as Partial<ReturnType<
      typeof createDefaultCreatorServicesConfig
    >>;
    delete legacy.video;
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => JSON.stringify(legacy)),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toMatchObject({
      video: createDefaultCreatorServicesConfig().video
    });
  });

  it('adds the credential-free Codex image defaults when reading an older saved configuration', async () => {
    const legacy = structuredClone(createDefaultCreatorServicesConfig()) as unknown as {
      image: Record<string, unknown>;
    };
    delete legacy.image.codexNative;
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => JSON.stringify(legacy)),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toMatchObject({
      image: { codexNative: {} }
    });
  });

  it('preserves older explicitly configured text models as custom', async () => {
    const legacy = createDefaultCreatorServicesConfig() as unknown as {
      llm: Record<string, unknown>;
    };
    delete legacy.llm.source;
    legacy.llm.baseUrl = 'https://legacy.example.test/v1';
    legacy.llm.apiKey = 'sk-legacy';
    legacy.llm.model = 'gpt-legacy';
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => JSON.stringify(legacy)),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toMatchObject({
      llm: { source: 'custom' }
    });
  });

  it('migrates the previous single image and video provider settings', async () => {
    const legacy = structuredClone(createDefaultCreatorServicesConfig()) as unknown as Record<string, unknown>;
    legacy.image = {
      provider: 'openai-compatible',
      openai: { baseUrl: 'https://images.example.test/v1', apiKey: 'old-image-key', model: 'gpt-image-1' }
    };
    legacy.video = {
      provider: 'openai-compatible',
      openai: { baseUrl: 'https://video.example.test/v1', apiKey: 'old-video-key', model: 'sora-2' }
    };
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => JSON.stringify(legacy)),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toMatchObject({
      image: {
        provider: 'openai',
        openai: { baseUrl: 'https://images.example.test/v1', apiKey: 'old-image-key', model: 'gpt-image-2' }
      },
      video: {
        provider: 'seedance',
        seedance: { apiKey: '', model: 'doubao-seedance-2-5-260628' }
      }
    });
  });

  it('migrates legacy TTS settings without treating Alibaba Cloud AK/SK as a Bailian API key', async () => {
    const legacy = structuredClone(createDefaultCreatorServicesConfig()) as unknown as Record<string, any>;
    legacy.tts = {
      provider: 'aliyun',
      openai: {
        baseUrl: '',
        apiKey: 'openai-key',
        model: 'gpt-4o-mini-tts'
      },
      minimax: {
        baseUrl: 'https://api.minimax.io',
        apiKey: 'minimax-key',
        model: 'speech-2.8-hd'
      },
      aliyun: {
        oss: {
          accessKeyId: 'old-oss-id',
          accessKeySecret: 'old-oss-secret',
          bucket: 'old-bucket'
        },
        speech: {
          accessKeyId: 'old-speech-id',
          accessKeySecret: 'old-speech-secret',
          appKey: 'old-app-key'
        }
      }
    };
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => JSON.stringify(legacy)),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).resolves.toMatchObject({
      tts: {
        provider: 'aliyun',
        openai: {
          apiKey: 'openai-key',
          defaultVoiceId: 'marin'
        },
        minimax: {
          apiKey: 'minimax-key',
          defaultVoiceId: 'English_Graceful_Lady'
        },
        aliyun: {
          baseUrl: 'https://dashscope.aliyuncs.com/api/v1',
          apiKey: '',
          model: 'qwen3-tts-flash',
          defaultVoiceId: 'Cherry'
        }
      }
    });
  });

  it('does not expose malformed stored values', async () => {
    const store = createCreatorServicesConfigStore({
      getPassword: vi.fn(async () => '{"llm":true}'),
      setPassword: vi.fn(async () => undefined),
      deletePassword: vi.fn(async () => undefined)
    });

    await expect(store.read()).rejects.toBeInstanceOf(CreatorServicesConfigStoreError);
  });
});