diff --git a/control-plane/src/catalog.ts b/control-plane/src/catalog.ts index 47c493c..6f9276b 100644 --- a/control-plane/src/catalog.ts +++ b/control-plane/src/catalog.ts @@ -76,6 +76,7 @@ export interface CatalogRepository { createApiKey(key: ApiKeyRecord): Promise listApiKeys(userId?: string): Promise findApiKeyByHash(keyHash: string): Promise + updateApiKeyModels(id: string, userId: string, modelIds: string[]): Promise revokeApiKey(id: string, userId: string, at: string): Promise touchApiKey(id: string, at: string): Promise } @@ -215,6 +216,14 @@ export class MemoryCatalogRepository implements CatalogRepository { return [...this.apiKeys.values()].find((key) => key.keyHash === keyHash) } + async updateApiKeyModels(id: string, userId: string, modelIds: string[]) { + const key = this.apiKeys.get(id) + if (!key || key.userId !== userId || key.status === 'disabled') return undefined + const updated = { ...key, modelIds: [...modelIds] } + this.apiKeys.set(id, updated) + return updated + } + async revokeApiKey(id: string, userId: string, at: string) { const key = this.apiKeys.get(id) if (!key || key.userId !== userId || key.status === 'disabled') return false @@ -322,7 +331,8 @@ export class CatalogService { 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 model = await this.repository.findModelById(modelId) + if (!model || model.status !== 'active') throw new CatalogError('MODEL_NOT_FOUND', `模型不存在或已下线:${modelId}`, 404) } if (input.projectId) { const project = await this.repository.findProjectById(input.projectId) @@ -350,6 +360,17 @@ export class CatalogService { return (await this.repository.listApiKeys(userId)).map(toPublicApiKey) } + async updateApiKeyModels(userId: string, id: string, inputModelIds: string[]) { + const modelIds = [...new Set(inputModelIds.map((modelId) => modelId.trim()).filter(Boolean))] + for (const modelId of modelIds) { + const model = await this.repository.findModelById(modelId) + if (!model || model.status !== 'active') throw new CatalogError('MODEL_NOT_FOUND', `模型不存在或已下线:${modelId}`, 404) + } + const updated = await this.repository.updateApiKeyModels(id, userId, modelIds) + if (!updated) throw new CatalogError('KEY_NOT_FOUND', 'Key 不存在、已停用或无权修改', 404) + return toPublicApiKey(updated) + } + 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) @@ -364,7 +385,7 @@ export class CatalogService { } canInvoke(record: ApiKeyRecord, modelId: string) { - return record.status === 'active' && record.scopes.includes('invoke') && (!record.modelIds.length || record.modelIds.includes(modelId)) + return record.status === 'active' && record.scopes.includes('invoke') && record.modelIds.includes(modelId) } } diff --git a/control-plane/src/server.ts b/control-plane/src/server.ts index cfdfdca..0fd6ed0 100644 --- a/control-plane/src/server.ts +++ b/control-plane/src/server.ts @@ -326,6 +326,16 @@ async function route(request: IncomingMessage, response: ServerResponse) { return } + const keyModelsMatch = path.match(/^\/api\/keys\/([^/]+)\/models$/) + const keyModelsId = keyModelsMatch?.[1] + if (method === 'POST' && keyModelsId) { + const user = await auth.requireUser(token) + const body = await readJson(request) + const apiKey = await catalog.updateApiKeyModels(user.id, keyModelsId, stringArrayValue(body.modelIds)) + send(response, 200, { apiKey }) + return + } + const keyRevokeMatch = path.match(/^\/api\/keys\/([^/]+)\/revoke$/) const keyId = keyRevokeMatch?.[1] if (method === 'POST' && keyId) { diff --git a/control-plane/tests/catalog.test.ts b/control-plane/tests/catalog.test.ts index 3024a92..85cda50 100644 --- a/control-plane/tests/catalog.test.ts +++ b/control-plane/tests/catalog.test.ts @@ -38,10 +38,22 @@ test('platform key is returned once, hashed at rest, and can be revoked', async test('key model allowlist is enforced by the service', async () => { const catalog = createCatalog() - const created = await catalog.createApiKey('user-1', { modelIds: ['model-mock-text'] }) + const created = await catalog.createApiKey('user-1', {}) + const unconfigured = await catalog.authenticateApiKey(created.key) - assert.equal(created.apiKey.modelIds[0], 'model-mock-text') + assert.deepEqual(created.apiKey.modelIds, []) assert.equal(created.apiKey.scopes.includes('invoke'), true) + assert.equal(catalog.canInvoke(unconfigured!, 'model-mock-text'), false) + + const updated = await catalog.updateApiKeyModels('user-1', created.apiKey.id, ['model-mock-3d', 'model-mock-3d']) + const configured = await catalog.authenticateApiKey(created.key) + assert.deepEqual(updated.modelIds, ['model-mock-3d']) + assert.equal(catalog.canInvoke(configured!, 'model-mock-3d'), true) + assert.equal(catalog.canInvoke(configured!, 'model-mock-text'), false) + await assert.rejects( + catalog.updateApiKeyModels('user-2', created.apiKey.id, ['model-mock-text']), + (error: unknown) => error instanceof Error && error.message === 'Key 不存在、已停用或无权修改', + ) }) test('personal and project keys can coexist with project ownership checks', async () => { diff --git a/prototype/src/services/catalog.ts b/prototype/src/services/catalog.ts index ed76a25..5177ede 100644 --- a/prototype/src/services/catalog.ts +++ b/prototype/src/services/catalog.ts @@ -155,6 +155,13 @@ class HttpCatalogClient { return this.request('/api/keys', { method: 'POST', body: JSON.stringify(input) }) } + async updateKeyModels(id: string, modelIds: string[]) { + return this.request<{ apiKey: CatalogApiKey }>(`/api/keys/${encodeURIComponent(id)}/models`, { + method: 'POST', + body: JSON.stringify({ modelIds }), + }) + } + async revokeKey(id: string) { await this.request(`/api/keys/${encodeURIComponent(id)}/revoke`, { method: 'POST' }) } diff --git a/prototype/src/styles.css b/prototype/src/styles.css index 76d6c84..9b5c642 100644 --- a/prototype/src/styles.css +++ b/prototype/src/styles.css @@ -195,3 +195,5 @@ td strong{font-size:12px} @media(max-width:900px){.playground-connection{align-items:flex-start;flex-wrap:wrap}.playground-connection>div{min-width:calc(100% - 52px)}.playground-connection>.button{margin-left:48px}.task-preview{height:210px}} @media(max-width:520px){.playground-connection>.button{width:100%;margin-left:0}.task-preview{height:190px}.live-task-head{align-items:flex-start;flex-direction:column}.live-task-actions{align-items:stretch;flex-wrap:wrap}.live-task-actions .button{flex:1}.request-panel,.response-panel{min-height:520px;padding:16px}} + +.model-permission-summary{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border:1px solid #dfe4ee;border-radius:7px;color:#5c4ade;background:#faf9ff;font-size:11px;cursor:pointer}.model-permission-summary:hover:not(:disabled){border-color:#b8acf9;background:#f3f0ff}.model-permission-summary:disabled{color:#98a2b3;background:#f7f8fa;cursor:not-allowed}.permission-hint{display:flex;align-items:flex-start;gap:8px;margin-top:18px;padding:11px 12px;border:1px solid #e4e0ff;border-radius:9px;color:#6252d7;background:#faf9ff;font-size:11px;line-height:1.5}.permission-hint svg{flex:0 0 auto;margin-top:1px}.permission-all-toggle,.permission-model-button{width:100%;display:flex;align-items:center;gap:10px;padding:12px 13px;border:1px solid #e4e7ef;border-radius:10px;background:#fff;color:var(--text);text-align:left;cursor:pointer}.permission-all-toggle{justify-content:space-between;margin-bottom:10px}.permission-all-toggle>span,.permission-model-button>span:nth-child(2){min-width:0;display:flex;flex:1;flex-direction:column;gap:3px}.permission-all-toggle strong,.permission-model-button strong{font-size:12px}.permission-all-toggle small,.permission-model-button small{overflow:hidden;color:var(--muted);font-size:10px;text-overflow:ellipsis;white-space:nowrap}.permission-all-toggle>span:first-child,.permission-model-button>span:first-child{display:flex;align-items:center;gap:8px}.permission-all-toggle i,.permission-model-button i{width:15px;height:15px;display:block;border:1.5px solid #cbd2df;border-radius:50%;background:#fff}.permission-all-toggle.active,.permission-model-button.active{border-color:#c7bcff;color:#5541d5;background:#faf9ff}.permission-all-toggle.active i,.permission-model-button.active i{border-color:#654de4;box-shadow:inset 0 0 0 4px #fff;background:#654de4}.permission-model-list{display:flex;max-height:290px;overflow:auto;flex-direction:column;gap:8px;padding-right:3px}.permission-model-button:hover{border-color:#b8acf9}.permission-model-button .model-icon{width:29px;height:29px;flex:0 0 29px}.modal-textarea{min-height:76px;resize:vertical}.modal-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:13px}@media(max-width:600px){.modal-form-grid{grid-template-columns:1fr}.permission-model-list{max-height:240px}} diff --git a/prototype/src/types.ts b/prototype/src/types.ts index 139296e..20c1f1a 100644 --- a/prototype/src/types.ts +++ b/prototype/src/types.ts @@ -38,6 +38,7 @@ export interface ApiKeyItem { scope: string scopeType?: 'personal' | 'project' projectId?: string + modelIds: string[] createdAt: string lastUsed: string status: '正常' | '已停用' diff --git a/prototype/src/views/AdminConsole.vue b/prototype/src/views/AdminConsole.vue index b5655e6..ae91e46 100644 --- a/prototype/src/views/AdminConsole.vue +++ b/prototype/src/views/AdminConsole.vue @@ -47,6 +47,18 @@ const selectedUser = ref(null) const invitationOpen = ref(false) const inviteLabel = ref('') const createdInviteCode = ref('') +const providerOpen = ref(false) +const providerCode = ref('') +const providerName = ref('') +const providerProtocol = ref('http') +const providerDescription = ref('') +const modelOpen = ref(false) +const modelProviderId = ref('') +const modelPublicName = ref('') +const modelUpstreamModel = ref('') +const modelType = ref('multimodal') +const modelMode = ref('sync') +const modelDescription = ref('') const auditQuery = ref('') const settings = reactive({ inviteOnly: false, emailSignup: false, phoneSignup: false, automaticCredit: false, maintenanceNotice: false, auditRetention: false }) @@ -108,15 +120,24 @@ function mapAudit(event: AdminAuditEvent) { } async function addProvider() { - const code = window.prompt('供应商 code(例如 zhipu)')?.trim() - const name = window.prompt('供应商名称')?.trim() - if (!code || !name) return + providerCode.value = '' + providerName.value = '' + providerProtocol.value = 'http' + providerDescription.value = '' + providerOpen.value = true +} + +async function createProvider() { + const code = providerCode.value.trim() + const name = providerName.value.trim() + if (!code || !name) return emit('notify', '请填写供应商 code 和名称') if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存供应商') try { - await catalogClient.createAdminProvider({ code, name, protocol: 'http', description: '由管理端登记的供应商适配位' }) + await catalogClient.createAdminProvider({ code, name, protocol: providerProtocol.value, description: providerDescription.value.trim() || undefined }) const result = await catalogClient.listAdminProviders() const modelsResult = await catalogClient.listAdminModels() providers.value = mapProviders(result.providers, modelsResult.models) + providerOpen.value = false emit('notify', '供应商已登记') } catch (error) { emit('notify', error instanceof Error ? error.message : '登记供应商失败') @@ -127,14 +148,26 @@ async function addModel() { if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型') const provider = providers.value[0] if (!provider) return emit('notify', '请先登记供应商') - const publicName = window.prompt('统一模型名称')?.trim() - const upstreamModel = window.prompt('上游模型标识')?.trim() - if (!publicName || !upstreamModel) return + modelProviderId.value = provider.id + modelPublicName.value = '' + modelUpstreamModel.value = '' + modelType.value = 'multimodal' + modelMode.value = 'sync' + modelDescription.value = '' + modelOpen.value = true +} + +async function createModel() { + const publicName = modelPublicName.value.trim() + const upstreamModel = modelUpstreamModel.value.trim() + if (!publicName || !upstreamModel) return emit('notify', '请填写统一模型名称和上游模型标识') + if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型') try { - await catalogClient.createAdminModel({ providerId: provider.id, publicName, upstreamModel, type: 'multimodal', mode: 'sync', description: '由管理端登记的模型目录项' }) + await catalogClient.createAdminModel({ providerId: modelProviderId.value, publicName, upstreamModel, type: modelType.value, mode: modelMode.value, description: modelDescription.value.trim() || undefined }) const [providerResult, modelResult] = await Promise.all([catalogClient.listAdminProviders(), catalogClient.listAdminModels()]) providers.value = mapProviders(providerResult.providers, modelResult.models) models.value = mapModels(modelResult.models, providerResult.providers) + modelOpen.value = false emit('notify', '模型已加入统一目录') } catch (error) { emit('notify', error instanceof Error ? error.message : '登记模型失败') @@ -230,5 +263,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
用户 ID
{{ selectedUser.id }}
额度余额
{{ selectedUser.balance === undefined ? '--(账本未接入)' : `¥ ${selectedUser.balance.toFixed(2)}` }}
累计用量
{{ selectedUser.usage || '--(用量统计未接入)' }}
最近活跃
{{ selectedUser.lastActive || '--' }}
{{ createdInviteCode }}
+ + diff --git a/prototype/src/views/UserConsole.vue b/prototype/src/views/UserConsole.vue index c71abbc..d751fa3 100644 --- a/prototype/src/views/UserConsole.vue +++ b/prototype/src/views/UserConsole.vue @@ -29,6 +29,7 @@ import { RefreshCcw, Search, ShieldCheck, + SlidersHorizontal, Sparkles, Terminal, Timer, @@ -60,10 +61,17 @@ const taskFilter = ref<'全部' | TaskStatus>('全部') const selectedTask = ref(null) const createKeyOpen = ref(false) const secretOpen = ref(false) +const projectOpen = ref(false) +const modelPermissionsOpen = ref(false) const keyName = ref('') -const keyScope = ref('全部模型') +const projectName = ref('') +const projectDescription = ref('') const createdSecret = ref('') +const createdKeyId = ref('') const revealSecret = ref(false) +const permissionKey = ref(null) +const selectedModelIds = ref([]) +const savingPermissions = ref(false) const projects = ref([]) const keyScopeType = ref<'personal' | 'project'>('personal') const selectedProjectId = ref('') @@ -122,6 +130,7 @@ const usageSeries = computed(() => { }) const recentTasks = computed(() => tasks.value.slice(0, 3)) const modelTypes: Array<'全部' | ModelType> = ['全部', '文本', '多模态', '图像', '3D', '视频', '音频'] +const allModelsSelected = computed(() => catalogModels.value.length > 0 && catalogModels.value.every((model) => selectedModelIds.value.includes(model.id))) async function copy(value: string, label: string, target: string) { const result = await copyText(value) @@ -265,6 +274,7 @@ async function createKey() { remoteApiKey.value = result.key keys.value.unshift(mapCatalogKey(result.apiKey, result.key)) createdSecret.value = result.key + createdKeyId.value = result.apiKey.id keyName.value = '' keyScopeType.value = 'personal' selectedProjectId.value = '' @@ -303,12 +313,63 @@ function mapCatalogKey(key: CatalogApiKey, plaintext = ''): ApiKeyItem { scope: key.scopeType === 'project' ? `项目 Key${key.projectId ? ` · ${key.projectId.slice(0, 12)}` : ''}` : '个人 Key', scopeType: key.scopeType, projectId: key.projectId, + modelIds: [...key.modelIds], createdAt: key.createdAt.slice(0, 10), lastUsed: key.lastUsedAt ? key.lastUsedAt.slice(0, 16).replace('T', ' ') : '尚未使用', status: key.status === 'active' ? '正常' : '已停用', } } +function openProjectModal() { + projectName.value = '' + projectDescription.value = '' + projectOpen.value = true +} + +function openModelPermissions(key: ApiKeyItem) { + if (key.status !== '正常') return emit('notify', '已停用的 Key 不能修改模型权限') + permissionKey.value = key + selectedModelIds.value = [...key.modelIds] + modelPermissionsOpen.value = true +} + +function openCreatedKeyPermissions() { + secretOpen.value = false + revealSecret.value = false + const key = keys.value.find((item) => item.id === createdKeyId.value) + if (key) openModelPermissions(key) +} + +function toggleModelPermission(modelId: string) { + selectedModelIds.value = selectedModelIds.value.includes(modelId) + ? selectedModelIds.value.filter((id) => id !== modelId) + : [...selectedModelIds.value, modelId] +} + +function toggleAllModels() { + selectedModelIds.value = allModelsSelected.value ? [] : catalogModels.value.map((model) => model.id) +} + +async function saveModelPermissions() { + const key = permissionKey.value + if (!key) return + if (!selectedModelIds.value.length) return emit('notify', '请至少选择一个可调用模型') + if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型权限') + savingPermissions.value = true + try { + const result = await catalogClient.updateKeyModels(String(key.id), selectedModelIds.value) + const index = keys.value.findIndex((item) => item.id === key.id) + if (index >= 0) keys.value[index] = { ...mapCatalogKey(result.apiKey), value: keys.value[index]!.value } + modelPermissionsOpen.value = false + permissionKey.value = null + emit('notify', `${key.name} 的模型权限已保存`) + } catch (error) { + emit('notify', error instanceof Error ? error.message : '保存模型权限失败') + } finally { + savingPermissions.value = false + } +} + async function toggleKey(key: ApiKeyItem) { if (catalogConnected.value && key.status === '正常') { try { @@ -324,15 +385,16 @@ async function toggleKey(key: ApiKeyItem) { } async function createProject() { - const name = window.prompt('请输入工作区/项目名称')?.trim() - if (!name) return + const name = projectName.value.trim() + if (!name) return emit('notify', '请输入工作区/项目名称') if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法创建真实项目') try { - const result = await catalogClient.createProject({ name }) - projects.value.unshift(result.project) - keyScopeType.value = 'project' - selectedProjectId.value = result.project.id - emit('notify', '项目已创建,可继续生成项目 Key') + const result = await catalogClient.createProject({ name, description: projectDescription.value.trim() || undefined }) + projects.value.unshift(result.project) + keyScopeType.value = 'project' + selectedProjectId.value = result.project.id + projectOpen.value = false + emit('notify', '项目已创建,可继续生成项目 Key') } catch (error) { emit('notify', error instanceof Error ? error.message : '创建项目失败') } @@ -415,7 +477,7 @@ async function createProject() {