feat: add mock key catalog and standard calls

This commit is contained in:
wlx committed 2026-08-23 19:21:31 +08:00
1 parent 78ed3c1103
commit 5e8e462548
8 files changed
+671 -8

No files matched your search

+217
View File
@@ -1,6 +1,8 @@
import { randomBytes } from 'node:crypto'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { parse as parseUrl } from 'node:url'
import { AuthError, AuthService, MemoryAuthRepository, type AuthRepository } from './auth.js'
import { CatalogService, MemoryCatalogRepository, type CallMode, type ModelType, type ProviderProtocol } from './catalog.js'
const config = {
host: process.env.CONTROL_PLANE_HOST || '127.0.0.1',
@@ -21,6 +23,17 @@ const auth = new AuthService(repository, {
sessionTtlHours: config.sessionTtlHours,
passwordPepper: config.passwordPepper,
})
const catalog = new CatalogService(new MemoryCatalogRepository())
type MockTask = {
id: string
userId: string
model: string
status: 'queued' | 'running' | 'succeeded'
createdAt: string
updatedAt: string
result?: { format: string; url: string }
}
const mockTasks = new Map<string, MockTask>()
if (config.nodeEnv === 'production' && (!process.env.AUTH_PASSWORD_PEPPER || process.env.AUTH_PASSWORD_PEPPER.length < 32)) {
throw new Error('AUTH_PASSWORD_PEPPER must contain at least 32 characters in production')
@@ -73,6 +86,71 @@ async function route(request: IncomingMessage, response: ServerResponse) {
}
const token = readCookie(request.headers.cookie, 'moyi_session')
if (method === 'GET' && path === '/v1/models') {
const keyRecord = await authenticatePlatformKey(request)
const models = await catalog.listModels()
send(response, 200, {
object: 'list',
data: models.filter((model) => catalog.canInvoke(keyRecord, model.id)).map((model) => ({
id: model.id,
object: 'model',
owned_by: model.providerId,
type: model.type,
mode: model.mode,
})),
})
return
}
if (method === 'POST' && path === '/v1/chat/completions') {
const keyRecord = await authenticatePlatformKey(request)
const body = await readJson(request)
const modelId = stringValue(body.model)
const model = await catalogModel(modelId)
if (model.mode === 'async') throw new AuthError('ASYNC_MODEL', '该模型需要使用异步任务接口', 400)
if (!catalog.canInvoke(keyRecord, model.id)) throw new AuthError('MODEL_FORBIDDEN', '当前 Key 无权调用该模型', 403)
const prompt = extractPrompt(body.messages)
send(response, 200, {
id: `chatcmpl-${randomToken(10)}`,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: model.id,
choices: [{ index: 0, message: { role: 'assistant', content: `MOYI Mock 已收到:${prompt || '(空消息)'}` }, finish_reason: 'stop' }],
usage: { prompt_tokens: prompt.length, completion_tokens: 12, total_tokens: prompt.length + 12 },
})
return
}
if (method === 'POST' && path === '/v1/3d/tasks') {
const keyRecord = await authenticatePlatformKey(request)
const body = await readJson(request)
const modelId = stringValue(body.model)
const model = await catalogModel(modelId)
if (model.type !== '3d' || model.mode !== 'async') throw new AuthError('NOT_ASYNC_3D_MODEL', '该模型不是异步 3D 模型', 400)
if (!catalog.canInvoke(keyRecord, model.id)) throw new AuthError('MODEL_FORBIDDEN', '当前 Key 无权调用该模型', 403)
const now = new Date().toISOString()
const task: MockTask = { id: `task_${randomToken(14)}`, userId: keyRecord.userId, model: model.id, status: 'queued', createdAt: now, updatedAt: now }
mockTasks.set(task.id, task)
setTimeout(() => {
const current = mockTasks.get(task.id)
if (!current) return
const updatedAt = new Date().toISOString()
mockTasks.set(task.id, { ...current, status: 'succeeded', updatedAt, result: { format: 'glb', url: `https://mock.moyi.ai/tasks/${task.id}/result.glb` } })
}, 500)
send(response, 202, { task: publicTask(task) })
return
}
const taskMatch = path.match(/^\/v1\/tasks\/([^/]+)$/)
const taskId = taskMatch?.[1]
if (method === 'GET' && taskId) {
const keyRecord = await authenticatePlatformKey(request)
const task = mockTasks.get(taskId)
if (!task || task.userId !== keyRecord.userId) throw new AuthError('TASK_NOT_FOUND', '任务不存在', 404)
send(response, 200, { task: publicTask(task) })
return
}
if (method === 'GET' && path === '/health') {
send(response, 200, { status: 'ok', service: 'moyi-control-plane' })
return
@@ -117,6 +195,42 @@ async function route(request: IncomingMessage, response: ServerResponse) {
return
}
if (method === 'GET' && path === '/api/models') {
await auth.requireUser(token)
send(response, 200, {
providers: await catalog.listProviders(),
models: await catalog.listModels(),
})
return
}
if (method === 'GET' && path === '/api/keys') {
const user = await auth.requireUser(token)
send(response, 200, { keys: await catalog.listApiKeys(user.id) })
return
}
if (method === 'POST' && path === '/api/keys') {
const user = await auth.requireUser(token)
const body = await readJson(request)
const result = await catalog.createApiKey(user.id, {
...(body.name ? { name: stringValue(body.name) } : {}),
...(body.scopes !== undefined ? { scopes: stringArrayValue(body.scopes) } : {}),
...(body.modelIds !== undefined ? { modelIds: stringArrayValue(body.modelIds) } : {}),
})
send(response, 201, result)
return
}
const keyRevokeMatch = path.match(/^\/api\/keys\/([^/]+)\/revoke$/)
const keyId = keyRevokeMatch?.[1]
if (method === 'POST' && keyId) {
const user = await auth.requireUser(token)
await catalog.revokeApiKey(user.id, keyId)
send(response, 204, undefined)
return
}
if (method === 'GET' && path === '/api/admin/users') {
send(response, 200, { users: await auth.listUsers(token) })
return
@@ -151,6 +265,52 @@ async function route(request: IncomingMessage, response: ServerResponse) {
return
}
if (method === 'GET' && path === '/api/admin/providers') {
await auth.requireAdmin(token)
send(response, 200, { providers: await catalog.listProviders(true) })
return
}
if (method === 'POST' && path === '/api/admin/providers') {
await auth.requireAdmin(token)
const body = await readJson(request)
const result = await catalog.createProvider({
code: stringValue(body.code),
name: stringValue(body.name),
protocol: providerProtocol(body.protocol),
...(body.baseUrl ? { baseUrl: stringValue(body.baseUrl) } : {}),
...(body.description ? { description: stringValue(body.description) } : {}),
})
send(response, 201, { provider: result })
return
}
if (method === 'GET' && path === '/api/admin/models') {
await auth.requireAdmin(token)
send(response, 200, { models: await catalog.listModels(true) })
return
}
if (method === 'POST' && path === '/api/admin/models') {
await auth.requireAdmin(token)
const body = await readJson(request)
const result = await catalog.createModel({
providerId: stringValue(body.providerId),
publicName: stringValue(body.publicName),
upstreamModel: stringValue(body.upstreamModel),
type: modelType(body.type),
mode: callMode(body.mode),
...(body.description ? { description: stringValue(body.description) } : {}),
...(body.inputTypes !== undefined ? { inputTypes: stringArrayValue(body.inputTypes) } : {}),
...(body.outputTypes !== undefined ? { outputTypes: stringArrayValue(body.outputTypes) } : {}),
...(body.capabilities && typeof body.capabilities === 'object' && !Array.isArray(body.capabilities)
? { capabilities: body.capabilities as Record<string, unknown> }
: {}),
})
send(response, 201, { model: result })
return
}
send(response, 404, { error: { code: 'NOT_FOUND', message: '接口不存在' } })
}
@@ -174,6 +334,63 @@ function stringValue(value: unknown) {
return typeof value === 'string' ? value : ''
}
async function authenticatePlatformKey(request: IncomingMessage) {
const authorization = request.headers.authorization || ''
const match = authorization.match(/^Bearer\s+(.+)$/i)
const record = await catalog.authenticateApiKey(match?.[1] || '')
if (!record) throw new AuthError('INVALID_API_KEY', 'MOYI API Key 无效或已停用', 401)
return record
}
async function catalogModel(id: string) {
const model = (await catalog.listModels()).find((item) => item.id === id)
if (!model) throw new AuthError('MODEL_NOT_FOUND', '模型不存在或已下线', 404)
return model
}
function extractPrompt(messages: unknown) {
if (!Array.isArray(messages)) return ''
const last = [...messages].reverse().find((message) => message && typeof message === 'object' && 'content' in message) as { content?: unknown } | undefined
return typeof last?.content === 'string' ? last.content : ''
}
function randomToken(length: number) {
return Buffer.from(randomBytes(Math.ceil(length * 0.75))).toString('base64url').slice(0, length)
}
function publicTask(task: MockTask) {
return {
id: task.id,
object: '3d.task',
model: task.model,
status: task.status,
created_at: task.createdAt,
updated_at: task.updatedAt,
...(task.result ? { result: task.result } : {}),
}
}
function stringArrayValue(value: unknown) {
if (!Array.isArray(value)) throw new AuthError('INVALID_ARRAY', '字段必须是字符串数组')
return value.filter((item): item is string => typeof item === 'string')
}
function providerProtocol(value: unknown): ProviderProtocol {
if (value === 'openai-compatible' || value === 'http' || value === 'sdk') return value
throw new AuthError('INVALID_PROVIDER_PROTOCOL', '供应商协议类型无效')
}
function modelType(value: unknown): ModelType {
const types: ModelType[] = ['text', 'code', 'multimodal', 'image', 'audio', 'video', 'embedding', '3d']
if (typeof value === 'string' && types.includes(value as ModelType)) return value as ModelType
throw new AuthError('INVALID_MODEL_TYPE', '模型类型无效')
}
function callMode(value: unknown): CallMode {
if (value === 'sync' || value === 'stream' || value === 'async') return value
throw new AuthError('INVALID_CALL_MODE', '调用模式无效')
}
function enforceAuthRateLimit(request: IncomingMessage, action: string) {
const now = Date.now()
const key = `${action}:${request.socket.remoteAddress || 'unknown'}`