feat: connect console to catalog and project keys
This commit is contained in:
1 parent
5e8e462548
commit
ec51e8c802
13 files changed
+503
-22
No files matched your search
@@ -38,6 +38,7 @@ pnpm dev
|
||||
- `GET /api/auth/me`:读取当前会话用户。
|
||||
- `POST /api/auth/logout`:撤销当前会话。
|
||||
- `GET /api/models`:读取当前可用的 Mock 模型和供应商目录。
|
||||
- `GET|POST /api/projects`:查看或创建当前用户拥有的工作区/项目。
|
||||
- `GET|POST /api/keys`:查看或创建平台调用 Key;明文 Key 只在创建响应中返回一次。
|
||||
- `POST /api/keys/:id/revoke`:撤销当前用户自己的平台 Key。
|
||||
- `GET /v1/models`:使用 `Authorization: Bearer <MOYI_KEY>` 查询可调用模型。
|
||||
@@ -57,5 +58,6 @@ pnpm dev
|
||||
- 数据库仅保存密码哈希、邀请码摘要和会话摘要,不保存明文密码、明文邀请码或会话 Token。
|
||||
- 生产环境必须设置随机的 `AUTH_PASSWORD_PEPPER`、强管理员密码和 HTTPS。
|
||||
- 管理员接口由 Control Plane 服务端角色校验保护,隐藏前端菜单不构成权限控制。
|
||||
- D4 的 Mock Key、模型目录暂存于内存仓库;PostgreSQL 迁移已准备 `model_providers`、`model_catalog` 和 `platform_api_keys` 表,接真实持久化时复用同一接口。
|
||||
- D4 的 Mock Key、项目和模型目录暂存于内存仓库;PostgreSQL 迁移已准备 `model_providers`、`model_catalog`、`model_projects` 和 `platform_api_keys` 表,接真实持久化时复用同一接口。
|
||||
- 额度界面统一按人民币 `¥` 展示;内测额度由管理员手动发放,真实计量、扣费和账单在后续节点实现。
|
||||
- 上游供应商密钥不进入模型目录或用户响应,后续由 Provider Adapter 通过环境变量/密钥管理服务读取。
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE IF NOT EXISTS model_projects (
|
||||
id varchar(64) PRIMARY KEY,
|
||||
owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name varchar(80) NOT NULL,
|
||||
description text NOT NULL DEFAULT '',
|
||||
status varchar(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE platform_api_keys ADD COLUMN IF NOT EXISTS project_id varchar(64) REFERENCES model_projects(id) ON DELETE CASCADE;
|
||||
CREATE INDEX IF NOT EXISTS model_projects_owner_user_id_idx ON model_projects(owner_user_id);
|
||||
CREATE INDEX IF NOT EXISTS platform_api_keys_project_id_idx ON platform_api_keys(project_id);
|
||||
@@ -37,6 +37,7 @@ export interface ModelRecord {
|
||||
export interface ApiKeyRecord {
|
||||
id: string
|
||||
userId: string
|
||||
projectId?: string
|
||||
name: string
|
||||
keyPrefix: string
|
||||
keyHash: string
|
||||
@@ -50,6 +51,8 @@ export interface ApiKeyRecord {
|
||||
|
||||
export interface PublicApiKey {
|
||||
id: string
|
||||
scopeType: 'personal' | 'project'
|
||||
projectId?: string
|
||||
name: string
|
||||
keyPrefix: string
|
||||
scopes: string[]
|
||||
@@ -61,6 +64,9 @@ export interface PublicApiKey {
|
||||
}
|
||||
|
||||
export interface CatalogRepository {
|
||||
listProjects(userId: string): Promise<ProjectRecord[]>
|
||||
findProjectById(id: string): Promise<ProjectRecord | undefined>
|
||||
createProject(project: ProjectRecord): Promise<void>
|
||||
listProviders(includeDisabled?: boolean): Promise<ProviderRecord[]>
|
||||
findProviderById(id: string): Promise<ProviderRecord | undefined>
|
||||
createProvider(provider: ProviderRecord): Promise<void>
|
||||
@@ -74,10 +80,21 @@ export interface CatalogRepository {
|
||||
touchApiKey(id: string, at: string): Promise<void>
|
||||
}
|
||||
|
||||
export interface ProjectRecord {
|
||||
id: string
|
||||
ownerUserId: string
|
||||
name: string
|
||||
description: string
|
||||
status: CatalogStatus
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export class MemoryCatalogRepository implements CatalogRepository {
|
||||
private readonly providers = new Map<string, ProviderRecord>()
|
||||
private readonly models = new Map<string, ModelRecord>()
|
||||
private readonly apiKeys = new Map<string, ApiKeyRecord>()
|
||||
private readonly projects = new Map<string, ProjectRecord>()
|
||||
|
||||
constructor() {
|
||||
const now = new Date().toISOString()
|
||||
@@ -142,6 +159,21 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
.sort((left, right) => left.name.localeCompare(right.name))
|
||||
}
|
||||
|
||||
async listProjects(userId: string) {
|
||||
return [...this.projects.values()]
|
||||
.filter((project) => project.ownerUserId === userId && project.status === 'active')
|
||||
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
|
||||
}
|
||||
|
||||
async findProjectById(id: string) {
|
||||
return this.projects.get(id)
|
||||
}
|
||||
|
||||
async createProject(project: ProjectRecord) {
|
||||
if (this.projects.has(project.id)) throw new CatalogError('PROJECT_EXISTS', '项目标识已存在', 409)
|
||||
this.projects.set(project.id, project)
|
||||
}
|
||||
|
||||
async findProviderById(id: string) {
|
||||
return this.providers.get(id)
|
||||
}
|
||||
@@ -262,7 +294,28 @@ export class CatalogService {
|
||||
return model
|
||||
}
|
||||
|
||||
async createApiKey(userId: string, input: { name?: string; scopes?: string[]; modelIds?: string[] }) {
|
||||
async listProjects(userId: string) {
|
||||
return this.repository.listProjects(userId)
|
||||
}
|
||||
|
||||
async createProject(userId: string, input: { name?: string; description?: string }) {
|
||||
const name = input.name?.trim() || ''
|
||||
if (!name || name.length > 80) throw new CatalogError('INVALID_PROJECT_NAME', '项目名称不能为空且不能超过 80 个字符')
|
||||
const now = new Date().toISOString()
|
||||
const project: ProjectRecord = {
|
||||
id: `project_${randomUUID().replaceAll('-', '').slice(0, 20)}`,
|
||||
ownerUserId: userId,
|
||||
name,
|
||||
description: input.description?.trim() || '',
|
||||
status: 'active',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
await this.repository.createProject(project)
|
||||
return project
|
||||
}
|
||||
|
||||
async createApiKey(userId: string, input: { name?: string; projectId?: 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))]
|
||||
@@ -271,11 +324,16 @@ export class CatalogService {
|
||||
for (const modelId of modelIds) {
|
||||
if (!await this.repository.findModelById(modelId)) throw new CatalogError('MODEL_NOT_FOUND', `模型不存在:${modelId}`, 404)
|
||||
}
|
||||
if (input.projectId) {
|
||||
const project = await this.repository.findProjectById(input.projectId)
|
||||
if (!project || project.ownerUserId !== userId || project.status !== 'active') throw new CatalogError('PROJECT_NOT_FOUND', '项目不存在或无权访问', 404)
|
||||
}
|
||||
const plaintext = `sk-moyi-${randomBytes(24).toString('base64url')}`
|
||||
const now = new Date().toISOString()
|
||||
const record: ApiKeyRecord = {
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
...(input.projectId ? { projectId: input.projectId } : {}),
|
||||
name,
|
||||
keyPrefix: plaintext.slice(0, 16),
|
||||
keyHash: hashSecret(plaintext),
|
||||
@@ -313,6 +371,8 @@ export class CatalogService {
|
||||
export function toPublicApiKey(key: ApiKeyRecord): PublicApiKey {
|
||||
return {
|
||||
id: key.id,
|
||||
scopeType: key.projectId ? 'project' : 'personal',
|
||||
...(key.projectId ? { projectId: key.projectId } : {}),
|
||||
name: key.name,
|
||||
keyPrefix: key.keyPrefix,
|
||||
scopes: [...key.scopes],
|
||||
|
||||
@@ -204,6 +204,23 @@ async function route(request: IncomingMessage, response: ServerResponse) {
|
||||
return
|
||||
}
|
||||
|
||||
if (method === 'GET' && path === '/api/projects') {
|
||||
const user = await auth.requireUser(token)
|
||||
send(response, 200, { projects: await catalog.listProjects(user.id) })
|
||||
return
|
||||
}
|
||||
|
||||
if (method === 'POST' && path === '/api/projects') {
|
||||
const user = await auth.requireUser(token)
|
||||
const body = await readJson(request)
|
||||
const project = await catalog.createProject(user.id, {
|
||||
name: stringValue(body.name),
|
||||
...(body.description ? { description: stringValue(body.description) } : {}),
|
||||
})
|
||||
send(response, 201, { project })
|
||||
return
|
||||
}
|
||||
|
||||
if (method === 'GET' && path === '/api/keys') {
|
||||
const user = await auth.requireUser(token)
|
||||
send(response, 200, { keys: await catalog.listApiKeys(user.id) })
|
||||
@@ -215,6 +232,7 @@ async function route(request: IncomingMessage, response: ServerResponse) {
|
||||
const body = await readJson(request)
|
||||
const result = await catalog.createApiKey(user.id, {
|
||||
...(body.name ? { name: stringValue(body.name) } : {}),
|
||||
...(body.projectId ? { projectId: stringValue(body.projectId) } : {}),
|
||||
...(body.scopes !== undefined ? { scopes: stringArrayValue(body.scopes) } : {}),
|
||||
...(body.modelIds !== undefined ? { modelIds: stringArrayValue(body.modelIds) } : {}),
|
||||
})
|
||||
|
||||
@@ -43,3 +43,18 @@ test('key model allowlist is enforced by the service', async () => {
|
||||
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 === '项目不存在或无权访问',
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user