import assert from 'node:assert/strict' import test from 'node:test' import { CatalogService, MemoryCatalogRepository } from '../src/catalog.js' import { hashSecret } from '../src/auth.js' function createCatalog() { return new CatalogService(new MemoryCatalogRepository()) } test('mock catalog contains sync multimodal and async 3D models', async () => { const catalog = createCatalog() const models = await catalog.listModels() assert.ok(models.some((model) => model.type === 'multimodal' && model.mode === 'sync')) assert.ok(models.some((model) => model.type === '3d' && model.mode === 'async')) }) test('platform key is returned once, hashed at rest, and can be revoked', async () => { const repository = new MemoryCatalogRepository() const catalog = new CatalogService(repository) const created = await catalog.createApiKey('user-1', { name: '验收 Key', modelIds: ['model-mock-text'] }) const listed = await catalog.listApiKeys('user-1') assert.match(created.key, /^sk-moyi-/) assert.equal(listed[0]?.keyPrefix, created.apiKey.keyPrefix) assert.equal('key' in listed[0]!, false) const stored = await repository.findApiKeyByHash(hashSecret(created.key)) assert.equal(stored?.keyHash, hashSecret(created.key)) assert.notEqual(stored?.keyHash, created.key) const authenticated = await catalog.authenticateApiKey(created.key) assert.ok(authenticated) assert.equal(catalog.canInvoke(authenticated!, 'model-mock-text'), true) assert.equal(catalog.canInvoke(authenticated!, 'model-mock-3d'), false) await catalog.revokeApiKey('user-1', created.apiKey.id) assert.equal(await catalog.authenticateApiKey(created.key), undefined) }) test('key model allowlist is enforced by the service', async () => { const catalog = createCatalog() const created = await catalog.createApiKey('user-1', { modelIds: ['model-mock-text'] }) assert.equal(created.apiKey.modelIds[0], 'model-mock-text') assert.equal(created.apiKey.scopes.includes('invoke'), true) }) test('personal and project keys can coexist with project ownership checks', async () => { const catalog = createCatalog() const project = await catalog.createProject('user-1', { name: 'AI SoulMate 联调' }) const personal = await catalog.createApiKey('user-1', { name: '个人调试' }) const projectKey = await catalog.createApiKey('user-1', { name: '项目服务', projectId: project.id }) assert.equal(personal.apiKey.scopeType, 'personal') assert.equal(projectKey.apiKey.scopeType, 'project') assert.equal(projectKey.apiKey.projectId, project.id) await assert.rejects( catalog.createApiKey('user-2', { projectId: project.id }), (error: unknown) => error instanceof Error && error.message === '项目不存在或无权访问', ) })