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
@@ -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) } : {}),
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user