import { randomBytes, randomUUID } from 'node:crypto' import { AuthError, hashSecret } from './auth.js' export type ModelType = 'text' | 'code' | 'multimodal' | 'image' | 'audio' | 'video' | 'embedding' | '3d' export type CallMode = 'sync' | 'stream' | 'async' export type ProviderProtocol = 'openai-compatible' | 'http' | 'sdk' export type CatalogStatus = 'active' | 'disabled' export interface ProviderRecord { id: string code: string name: string protocol: ProviderProtocol baseUrl?: string description?: string status: CatalogStatus createdAt: string updatedAt: string } export interface ModelRecord { id: string providerId: string publicName: string upstreamModel: string type: ModelType mode: CallMode description: string inputTypes: string[] outputTypes: string[] capabilities: Record status: CatalogStatus createdAt: string updatedAt: string } export interface ApiKeyRecord { id: string userId: string name: string keyPrefix: string keyHash: string scopes: string[] modelIds: string[] status: CatalogStatus createdAt: string lastUsedAt?: string revokedAt?: string } export interface PublicApiKey { id: string name: string keyPrefix: string scopes: string[] modelIds: string[] status: CatalogStatus createdAt: string lastUsedAt?: string revokedAt?: string } export interface CatalogRepository { listProviders(includeDisabled?: boolean): Promise findProviderById(id: string): Promise createProvider(provider: ProviderRecord): Promise listModels(includeDisabled?: boolean): Promise findModelById(id: string): Promise createModel(model: ModelRecord): Promise createApiKey(key: ApiKeyRecord): Promise listApiKeys(userId?: string): Promise findApiKeyByHash(keyHash: string): Promise revokeApiKey(id: string, userId: string, at: string): Promise touchApiKey(id: string, at: string): Promise } export class MemoryCatalogRepository implements CatalogRepository { private readonly providers = new Map() private readonly models = new Map() private readonly apiKeys = new Map() constructor() { const now = new Date().toISOString() const mockProvider: ProviderRecord = { id: 'provider-mock', code: 'moyi-mock', name: 'MOYI Mock Provider', protocol: 'http', baseUrl: 'http://mock.local', description: '用于控制台联调的 Mock 供应商,不代表真实上游能力。', status: 'active', createdAt: now, updatedAt: now, } const vastProvider: ProviderRecord = { id: 'provider-vast', code: 'vast', name: 'VAST / Tripo', protocol: 'http', description: '预留 3D 生成供应商适配位,D4 先登记目录。', status: 'active', createdAt: now, updatedAt: now, } this.providers.set(mockProvider.id, mockProvider) this.providers.set(vastProvider.id, vastProvider) this.models.set('model-mock-text', { id: 'model-mock-text', providerId: mockProvider.id, publicName: 'MOYI Text Pro (Mock)', upstreamModel: 'moyi-mock-text-v1', type: 'multimodal', mode: 'sync', description: '同步文本/代码/图像理解模型,用于首轮 HTTP 和 SDK 验收。', inputTypes: ['text', 'image'], outputTypes: ['text'], capabilities: { streaming: true, vision: true, toolCalling: true }, status: 'active', createdAt: now, updatedAt: now, }) this.models.set('model-mock-3d', { id: 'model-mock-3d', providerId: vastProvider.id, publicName: 'VAST 3D Generator (Mock)', upstreamModel: 'tripo-mock-3d-v1', type: '3d', mode: 'async', description: '异步 3D 生成模型,预留任务创建、轮询和回调字段。', inputTypes: ['text', 'image'], outputTypes: ['model', 'thumbnail'], capabilities: { taskPolling: true, webhook: true, formats: ['glb', 'obj', 'fbx'] }, status: 'active', createdAt: now, updatedAt: now, }) } async listProviders(includeDisabled = false) { return [...this.providers.values()] .filter((provider) => includeDisabled || provider.status === 'active') .sort((left, right) => left.name.localeCompare(right.name)) } async findProviderById(id: string) { return this.providers.get(id) } async createProvider(provider: ProviderRecord) { if (this.providers.has(provider.id) || [...this.providers.values()].some((item) => item.code === provider.code)) { throw new CatalogError('PROVIDER_EXISTS', '供应商标识已存在', 409) } this.providers.set(provider.id, provider) } async listModels(includeDisabled = false) { return [...this.models.values()] .filter((model) => includeDisabled || model.status === 'active') .sort((left, right) => left.publicName.localeCompare(right.publicName)) } async findModelById(id: string) { return this.models.get(id) } async createModel(model: ModelRecord) { if (this.models.has(model.id)) throw new CatalogError('MODEL_EXISTS', '模型标识已存在', 409) if (!this.providers.has(model.providerId)) throw new CatalogError('PROVIDER_NOT_FOUND', '供应商不存在', 404) this.models.set(model.id, model) } async createApiKey(key: ApiKeyRecord) { this.apiKeys.set(key.id, key) } async listApiKeys(userId?: string) { return [...this.apiKeys.values()] .filter((key) => !userId || key.userId === userId) .sort((left, right) => right.createdAt.localeCompare(left.createdAt)) } async findApiKeyByHash(keyHash: string) { return [...this.apiKeys.values()].find((key) => key.keyHash === keyHash) } async revokeApiKey(id: string, userId: string, at: string) { const key = this.apiKeys.get(id) if (!key || key.userId !== userId || key.status === 'disabled') return false this.apiKeys.set(id, { ...key, status: 'disabled', revokedAt: at }) return true } async touchApiKey(id: string, at: string) { const key = this.apiKeys.get(id) if (key) this.apiKeys.set(id, { ...key, lastUsedAt: at }) } } export class CatalogError extends AuthError {} export class CatalogService { constructor(private readonly repository: CatalogRepository) {} async listModels(includeDisabled = false) { return this.repository.listModels(includeDisabled) } async listProviders(includeDisabled = false) { return this.repository.listProviders(includeDisabled) } async createProvider(input: { code: string; name: string; protocol: ProviderProtocol; baseUrl?: string; description?: string }) { const code = input.code.trim().toLowerCase() const name = input.name.trim() if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(code) || !name) throw new CatalogError('INVALID_PROVIDER', '供应商 code 和名称不能为空且格式无效') const now = new Date().toISOString() const provider: ProviderRecord = { id: randomUUID(), code, name, protocol: input.protocol, ...(input.baseUrl?.trim() ? { baseUrl: input.baseUrl.trim() } : {}), ...(input.description?.trim() ? { description: input.description.trim() } : {}), status: 'active', createdAt: now, updatedAt: now, } await this.repository.createProvider(provider) return provider } async createModel(input: { providerId: string publicName: string upstreamModel: string type: ModelType mode: CallMode description?: string inputTypes?: string[] outputTypes?: string[] capabilities?: Record }) { if (!input.publicName.trim() || !input.upstreamModel.trim()) throw new CatalogError('INVALID_MODEL', '模型名称和上游模型标识不能为空') if (!await this.repository.findProviderById(input.providerId)) throw new CatalogError('PROVIDER_NOT_FOUND', '供应商不存在', 404) const now = new Date().toISOString() const model: ModelRecord = { id: randomUUID(), providerId: input.providerId, publicName: input.publicName.trim(), upstreamModel: input.upstreamModel.trim(), type: input.type, mode: input.mode, description: input.description?.trim() || '', inputTypes: input.inputTypes || [], outputTypes: input.outputTypes || [], capabilities: input.capabilities || {}, status: 'active', createdAt: now, updatedAt: now, } await this.repository.createModel(model) return model } async createApiKey(userId: string, input: { name?: string; scopes?: string[]; modelIds?: string[] }) { const name = input.name?.trim() || '默认开发 Key' if (name.length > 80) throw new CatalogError('INVALID_KEY_NAME', 'Key 名称不能超过 80 个字符') const scopes = [...new Set((input.scopes?.length ? input.scopes : ['invoke']).map((scope) => scope.trim()).filter(Boolean))] if (!scopes.length || scopes.some((scope) => !/^[a-z][a-z:_-]{1,31}$/.test(scope))) throw new CatalogError('INVALID_KEY_SCOPE', 'Key 权限范围格式无效') const modelIds = [...new Set(input.modelIds || [])] for (const modelId of modelIds) { if (!await this.repository.findModelById(modelId)) throw new CatalogError('MODEL_NOT_FOUND', `模型不存在:${modelId}`, 404) } const plaintext = `sk-moyi-${randomBytes(24).toString('base64url')}` const now = new Date().toISOString() const record: ApiKeyRecord = { id: randomUUID(), userId, name, keyPrefix: plaintext.slice(0, 16), keyHash: hashSecret(plaintext), scopes, modelIds, status: 'active', createdAt: now, } await this.repository.createApiKey(record) return { key: plaintext, apiKey: toPublicApiKey(record) } } async listApiKeys(userId: string) { return (await this.repository.listApiKeys(userId)).map(toPublicApiKey) } async revokeApiKey(userId: string, id: string) { const changed = await this.repository.revokeApiKey(id, userId, new Date().toISOString()) if (!changed) throw new CatalogError('KEY_NOT_FOUND', 'Key 不存在或已停用', 404) } async authenticateApiKey(plaintext: string) { if (!plaintext.trim()) return undefined const record = await this.repository.findApiKeyByHash(hashSecret(plaintext.trim())) if (!record || record.status !== 'active') return undefined await this.repository.touchApiKey(record.id, new Date().toISOString()) return record } canInvoke(record: ApiKeyRecord, modelId: string) { return record.status === 'active' && record.scopes.includes('invoke') && (!record.modelIds.length || record.modelIds.includes(modelId)) } } export function toPublicApiKey(key: ApiKeyRecord): PublicApiKey { return { id: key.id, name: key.name, keyPrefix: key.keyPrefix, scopes: [...key.scopes], modelIds: [...key.modelIds], status: key.status, createdAt: key.createdAt, ...(key.lastUsedAt ? { lastUsedAt: key.lastUsedAt } : {}), ...(key.revokedAt ? { revokedAt: key.revokedAt } : {}), } }