feat: scope API MCP OAuth by principal

This commit is contained in:
wizardchen
2026-06-30 09:21:49 +08:00
committed by lyingbug
parent 77e4f93e3e
commit cb99736d72
39 changed files with 1566 additions and 108 deletions
+45
View File
@@ -17,6 +17,22 @@ export interface TenantInfo {
updated_at: string
}
export type APIPrincipalMode = 'tenant' | 'direct_header' | 'signed_token'
export interface APIPrincipalConfig {
mode: APIPrincipalMode
direct_header_name: string
signed_token_header_name: string
has_hmac_secret: boolean
}
export interface UpdateAPIPrincipalConfigPayload {
mode: APIPrincipalMode
direct_header_name?: string
signed_token_header_name?: string
hmac_secret?: string
}
// 搜索租户参数
export interface SearchTenantsParams {
keyword?: string
@@ -70,6 +86,35 @@ export async function resetTenantApiKey(
}
}
export async function getAPIPrincipalConfig(
tenantId: number,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await get(`/api/v1/tenants/${tenantId}/api-principal-config`)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.getApiPrincipalConfigFailed'),
}
}
}
export async function updateAPIPrincipalConfig(
tenantId: number,
payload: UpdateAPIPrincipalConfigPayload,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await put(`/api/v1/tenants/${tenantId}/api-principal-config`, payload)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.updateApiPrincipalConfigFailed'),
}
}
}
/**
* 更新租户信息(目前暴露名称、描述两个字段的编辑入口)。
* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会
+3 -2
View File
@@ -3,9 +3,9 @@ export const CHROME_EXTENSION_URL =
export const CLAWHUB_SKILL_URL = 'https://clawhub.ai/lyingbug/weknora'
export type IntegrationTab = 'im' | 'embed' | 'chrome' | 'claw'
export type IntegrationTab = 'im' | 'embed' | 'api' | 'chrome' | 'claw'
export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'chrome', 'claw']
export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'chrome', 'claw']
export type IntegrationPreviewIcon =
| { type: 'icon'; name: string }
@@ -18,6 +18,7 @@ export const INTEGRATION_PREVIEW_ITEMS: Array<{
}> = [
{ key: 'im', icon: { type: 'icon', name: 'chat-message' } },
{ key: 'embed', icon: { type: 'icon', name: 'code' } },
{ key: 'api', icon: { type: 'icon', name: 'api' } },
{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },
{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },
]
+32
View File
@@ -3635,6 +3635,8 @@ export default {
listFailed: 'Failed to list tenants',
searchFailed: 'Failed to search tenants',
resetApiKeyFailed: 'Failed to reset API Key',
getApiPrincipalConfigFailed: 'Failed to get API principal config',
updateApiPrincipalConfigFailed: 'Failed to update API principal config',
updateFailed: 'Failed to update tenant information',
deleteFailed: 'Failed to delete tenant',
},
@@ -5737,9 +5739,39 @@ export default {
tabs: {
im: 'IM Integration',
embed: 'Web Embed',
api: 'API Key',
chrome: 'Chrome Extension',
claw: 'Claw Skill',
},
api: {
title: 'API Key Integration',
subtitle: 'Use the tenant API key for server-side integrations, and choose how API requests identify the terminal user.',
loading: 'Loading API integration settings...',
retry: 'Retry',
copy: 'Copy',
copySuccess: 'Copied',
save: 'Save',
baseUrl: 'API Base URL',
baseUrlDesc: 'Use this base URL with REST API paths.',
apiKey: 'Tenant API Key',
apiKeyDesc: 'The API key is still tenant-level. User identity is supplied by the principal mode below.',
principalMode: 'User identity mode',
principalModeDesc: 'Controls how X-API-Key requests map to a principal for OAuth MCP tokens and other per-user features.',
modeTenant: 'Tenant only',
modeDirect: 'Direct user ID',
modeSigned: 'Signed token',
directWarning: 'Direct user ID trusts the caller-supplied header. Use only for trusted server-to-server calls.',
signedRecommended: 'Recommended for user-facing apps: your backend signs a short-lived HS256 JWT for the external user.',
directHeader: 'User ID header',
tokenHeader: 'Token header',
hmacSecret: 'HMAC secret',
secretConfigured: 'Secret configured; enter a new value to rotate',
generateSecret: 'Generate secret',
requestExample: 'Request example',
loadFailed: 'Failed to load API integration settings',
saveFailed: 'Failed to save API integration settings',
saveSuccess: 'API integration settings saved',
},
manageSectionTitle: 'Channel configuration',
manageSectionDesc: 'Select an agent to create or edit integration channels for that agent',
selectAgent: 'Select agent',
+32
View File
@@ -2643,6 +2643,8 @@ export default {
listFailed: '테넌트 목록 조회 실패',
searchFailed: '테넌트 검색 실패',
resetApiKeyFailed: 'API 키 재설정 실패',
getApiPrincipalConfigFailed: 'API principal config 조회 실패',
updateApiPrincipalConfigFailed: 'API principal config 업데이트 실패',
updateFailed: '테넌트 정보 업데이트 실패',
},
initialization: {
@@ -5748,9 +5750,39 @@ export default {
tabs: {
im: "IM 통합",
embed: "웹 임베드",
api: "API Key",
chrome: "Chrome 확장",
claw: "Claw Skill",
},
api: {
title: "API Key 통합",
subtitle: "테넌트 API Key로 서버 연동을 구성하고, API 요청이 최종 사용자 ID를 전달하는 방식을 선택합니다.",
loading: "API 통합 설정을 불러오는 중...",
retry: "다시 시도",
copy: "복사",
copySuccess: "복사되었습니다",
save: "저장",
baseUrl: "API Base URL",
baseUrlDesc: "REST API 경로와 함께 사용하세요.",
apiKey: "테넌트 API Key",
apiKeyDesc: "API Key는 계속 테넌트 단위입니다. 사용자 ID는 아래 모드로 전달합니다.",
principalMode: "사용자 ID 모드",
principalModeDesc: "X-API-Key 요청을 Principal로 매핑하는 방식입니다. OAuth MCP 토큰 및 사용자별 기능에 사용됩니다.",
modeTenant: "테넌트만",
modeDirect: "사용자 ID 직접 전달",
modeSigned: "서명 토큰",
directWarning: "직접 사용자 ID 모드는 요청 헤더를 신뢰합니다. 신뢰된 서버 간 호출에만 사용하세요.",
signedRecommended: "사용자 대상 앱에는 권장됩니다. 비즈니스 백엔드가 외부 사용자용 단기 HS256 JWT를 서명합니다.",
directHeader: "사용자 ID 헤더",
tokenHeader: "토큰 헤더",
hmacSecret: "HMAC secret",
secretConfigured: "Secret configured; enter a new value to rotate",
generateSecret: "Secret 생성",
requestExample: "요청 예시",
loadFailed: "API 통합 설정을 불러오지 못했습니다",
saveFailed: "API 통합 설정 저장 실패",
saveSuccess: "API 통합 설정이 저장되었습니다",
},
manageSectionTitle: "채널 구성",
manageSectionDesc: "에이전트를 선택한 후 해당 에이전트의 통합 채널을 생성하거나 편집할 수 있습니다",
selectAgent: "에이전트 선택",
+32
View File
@@ -2653,6 +2653,8 @@ export default {
listFailed: "获取空间列表失败",
searchFailed: "搜索空间失败",
resetApiKeyFailed: "重置 API Key 失败",
getApiPrincipalConfigFailed: "获取 API 用户身份配置失败",
updateApiPrincipalConfigFailed: "更新 API 用户身份配置失败",
updateFailed: "更新空间信息失败",
deleteFailed: "删除空间失败",
},
@@ -5750,9 +5752,39 @@ export default {
tabs: {
im: "IM 集成",
embed: "网页嵌入",
api: "API Key",
chrome: "Chrome 插件",
claw: "Claw Skill",
},
api: {
title: "API Key 集成",
subtitle: "使用租户级 API Key 接入服务,并选择 API 请求如何携带终端用户身份。",
loading: "正在加载 API 集成设置...",
retry: "重试",
copy: "复制",
copySuccess: "已复制",
save: "保存",
baseUrl: "API 地址",
baseUrlDesc: "与 REST API 路径拼接使用。",
apiKey: "租户 API Key",
apiKeyDesc: "API Key 仍按租户级管理;终端用户身份由下方模式提供。",
principalMode: "用户身份模式",
principalModeDesc: "决定 X-API-Key 请求如何映射为 Principal,用于 OAuth MCP token 和其他按用户隔离的能力。",
modeTenant: "仅租户",
modeDirect: "直接传用户 ID",
modeSigned: "签名 Token",
directWarning: "直接传用户 ID 会信任调用方请求头,仅建议用于可信服务端到服务端调用。",
signedRecommended: "推荐给面向用户的应用:业务方后端为外部用户签发短期 HS256 JWT。",
directHeader: "用户 ID 请求头",
tokenHeader: "Token 请求头",
hmacSecret: "HMAC 密钥",
secretConfigured: "已配置密钥;输入新值可轮换",
generateSecret: "生成密钥",
requestExample: "请求示例",
loadFailed: "加载 API 集成设置失败",
saveFailed: "保存 API 集成设置失败",
saveSuccess: "API 集成设置已保存",
},
manageSectionTitle: "渠道配置",
manageSectionDesc: "选择智能体后,可创建或编辑该智能体下的集成渠道",
selectAgent: "选择智能体",
@@ -0,0 +1,372 @@
<template>
<div class="api-integration section">
<div class="section-header">
<h2>{{ $t('integrations.api.title') }}</h2>
<p class="section-description">{{ $t('integrations.api.subtitle') }}</p>
</div>
<div v-if="loading" class="state-row">
<t-loading size="small" />
<span>{{ $t('integrations.api.loading') }}</span>
</div>
<t-alert v-else-if="error" theme="error" :message="error">
<template #operation>
<t-button size="small" @click="load">{{ $t('integrations.api.retry') }}</t-button>
</template>
</t-alert>
<div v-else class="api-settings">
<section class="settings-band">
<div class="row">
<div class="row-info">
<label>{{ $t('integrations.api.baseUrl') }}</label>
<p>{{ $t('integrations.api.baseUrlDesc') }}</p>
</div>
<div class="row-control copy-field">
<t-input :model-value="apiBaseUrl" readonly class="mono-input" />
<t-button variant="text" :title="$t('integrations.api.copy')" @click="copy(apiBaseUrl)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
<div class="row">
<div class="row-info">
<label>{{ $t('integrations.api.apiKey') }}</label>
<p>{{ $t('integrations.api.apiKeyDesc') }}</p>
</div>
<div class="row-control copy-field">
<t-input :model-value="displayApiKey" readonly class="mono-input" />
<t-button variant="text" @click="showApiKey = !showApiKey">
<t-icon :name="showApiKey ? 'browse-off' : 'browse'" />
</t-button>
<t-button variant="text" :title="$t('integrations.api.copy')" @click="copy(apiKey)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
</section>
<section class="settings-band">
<div class="row row--stack">
<div class="row-info">
<label>{{ $t('integrations.api.principalMode') }}</label>
<p>{{ $t('integrations.api.principalModeDesc') }}</p>
</div>
<div class="mode-panel">
<t-radio-group v-model="form.mode">
<t-radio-button value="tenant">{{ $t('integrations.api.modeTenant') }}</t-radio-button>
<t-radio-button value="direct_header">{{ $t('integrations.api.modeDirect') }}</t-radio-button>
<t-radio-button value="signed_token">{{ $t('integrations.api.modeSigned') }}</t-radio-button>
</t-radio-group>
<t-alert
v-if="form.mode === 'direct_header'"
theme="warning"
:message="$t('integrations.api.directWarning')"
/>
<t-alert
v-if="form.mode === 'signed_token'"
theme="success"
:message="$t('integrations.api.signedRecommended')"
/>
<div v-if="form.mode === 'direct_header'" class="field-grid">
<label>{{ $t('integrations.api.directHeader') }}</label>
<t-input v-model="form.direct_header_name" class="mono-input" />
</div>
<div v-if="form.mode === 'signed_token'" class="field-grid">
<label>{{ $t('integrations.api.tokenHeader') }}</label>
<t-input v-model="form.signed_token_header_name" class="mono-input" />
<label>{{ $t('integrations.api.hmacSecret') }}</label>
<div class="copy-field">
<t-input
v-model="secretInput"
type="password"
class="mono-input"
:placeholder="config?.has_hmac_secret ? $t('integrations.api.secretConfigured') : ''"
/>
<t-button variant="text" :title="$t('integrations.api.generateSecret')" @click="generateSecret">
<t-icon name="refresh" />
</t-button>
</div>
</div>
<div class="example-box">
<div class="example-title">{{ $t('integrations.api.requestExample') }}</div>
<pre>{{ requestExample }}</pre>
</div>
<div class="actions">
<t-button theme="primary" :loading="saving" :disabled="!canSave" @click="save">
{{ $t('integrations.api.save') }}
</t-button>
</div>
</div>
</div>
</section>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { getCurrentUser } from '@/api/auth'
import {
getAPIPrincipalConfig,
updateAPIPrincipalConfig,
type APIPrincipalConfig,
type APIPrincipalMode,
} from '@/api/tenant'
import { getApiBaseUrl } from '@/utils/api-base'
const { t } = useI18n()
const loading = ref(true)
const saving = ref(false)
const error = ref('')
const tenantId = ref(0)
const apiKey = ref('')
const showApiKey = ref(false)
const config = ref<APIPrincipalConfig | null>(null)
const secretInput = ref('')
const form = reactive({
mode: 'tenant' as APIPrincipalMode,
direct_header_name: 'X-External-User-ID',
signed_token_header_name: 'X-External-User-Token',
})
const apiBaseUrl = computed(() => {
const configured = getApiBaseUrl().trim().replace(/\/$/, '')
const origin = typeof window !== 'undefined' && window.location.origin !== 'null' ? window.location.origin : ''
return `${configured || origin}/api/v1`
})
const displayApiKey = computed(() => {
if (!apiKey.value) return ''
if (showApiKey.value) return apiKey.value
return '•'.repeat(apiKey.value.length)
})
const canSave = computed(() => {
if (!tenantId.value) return false
if (form.mode === 'signed_token') {
return config.value?.has_hmac_secret === true || secretInput.value.trim() !== ''
}
return true
})
const requestExample = computed(() => {
const lines = [
`curl -X POST ${apiBaseUrl.value}/session/qa`,
` -H "X-API-Key: ${apiKey.value ? '<API_KEY>' : '<YOUR_API_KEY>'}"`,
` -H "Content-Type: application/json"`,
]
if (form.mode === 'direct_header') {
lines.push(` -H "${form.direct_header_name || 'X-External-User-ID'}: user_123"`)
}
if (form.mode === 'signed_token') {
lines.push(` -H "${form.signed_token_header_name || 'X-External-User-Token'}: <HS256_JWT>"`)
}
lines.push(` -d '{"query":"hello"}'`)
return lines.join(' \\\n')
})
async function load() {
loading.value = true
error.value = ''
try {
const userResp = await getCurrentUser()
const tenant = (userResp as any)?.data?.tenant
if (!tenant?.id) {
throw new Error(t('integrations.api.loadFailed'))
}
tenantId.value = Number(tenant.id)
apiKey.value = tenant.api_key || ''
const cfgResp = await getAPIPrincipalConfig(tenantId.value)
if (!cfgResp.success || !cfgResp.data) {
throw new Error(cfgResp.message || t('integrations.api.loadFailed'))
}
config.value = cfgResp.data
form.mode = cfgResp.data.mode || 'tenant'
form.direct_header_name = cfgResp.data.direct_header_name || 'X-External-User-ID'
form.signed_token_header_name = cfgResp.data.signed_token_header_name || 'X-External-User-Token'
secretInput.value = ''
} catch (err: any) {
error.value = err?.message || t('integrations.api.loadFailed')
} finally {
loading.value = false
}
}
function generateSecret() {
const bytes = new Uint8Array(32)
window.crypto.getRandomValues(bytes)
secretInput.value = btoa(String.fromCharCode(...bytes))
}
async function save() {
if (!tenantId.value) return
saving.value = true
try {
const payload: Parameters<typeof updateAPIPrincipalConfig>[1] = {
mode: form.mode,
direct_header_name: form.direct_header_name.trim(),
signed_token_header_name: form.signed_token_header_name.trim(),
}
if (secretInput.value.trim()) {
payload.hmac_secret = secretInput.value.trim()
}
const resp = await updateAPIPrincipalConfig(tenantId.value, payload)
if (!resp.success || !resp.data) {
throw new Error(resp.message || t('integrations.api.saveFailed'))
}
config.value = resp.data
secretInput.value = ''
MessagePlugin.success(t('integrations.api.saveSuccess'))
} catch (err: any) {
MessagePlugin.error(err?.message || t('integrations.api.saveFailed'))
} finally {
saving.value = false
}
}
async function copy(text: string) {
if (!text) return
await navigator.clipboard.writeText(text)
MessagePlugin.success(t('integrations.api.copySuccess'))
}
onMounted(load)
</script>
<style scoped lang="less">
.api-integration {
width: 100%;
}
.state-row {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
min-height: 160px;
color: var(--td-text-color-secondary);
}
.api-settings,
.settings-band {
display: flex;
flex-direction: column;
}
.settings-band {
border-top: 1px solid var(--td-component-stroke);
}
.row {
display: grid;
grid-template-columns: minmax(220px, 0.8fr) minmax(320px, 1fr);
gap: 24px;
padding: 20px 0;
border-bottom: 1px solid var(--td-component-stroke);
}
.row--stack {
grid-template-columns: minmax(220px, 0.8fr) minmax(420px, 1fr);
}
.row-info {
label {
display: block;
margin-bottom: 4px;
color: var(--td-text-color-primary);
font-size: 15px;
font-weight: 600;
}
p {
margin: 0;
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 1.5;
}
}
.row-control,
.copy-field {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.mode-panel {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.field-grid {
display: grid;
grid-template-columns: 130px minmax(0, 1fr);
gap: 10px 12px;
align-items: center;
label {
color: var(--td-text-color-secondary);
font-size: 13px;
}
}
.example-box {
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
background: var(--td-bg-color-page);
overflow: hidden;
}
.example-title {
padding: 10px 12px;
border-bottom: 1px solid var(--td-component-stroke);
color: var(--td-text-color-secondary);
font-size: 12px;
}
pre {
margin: 0;
padding: 12px;
overflow: auto;
font-family: var(--app-font-family-mono);
font-size: 12px;
line-height: 1.6;
}
.actions {
display: flex;
justify-content: flex-end;
}
.mono-input :deep(input) {
font-family: var(--app-font-family-mono);
font-size: 12px;
}
@media (max-width: 780px) {
.row,
.row--stack {
grid-template-columns: 1fr;
}
.field-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -57,6 +57,7 @@
<AgentEmbedChannelPanel v-model:filter-agent-id="filterAgentId" />
</div>
<ApiIntegrationSettings v-if="currentSection === 'api'" />
<ChromeExtensionLanding v-if="currentSection === 'chrome'" />
<ClawSkillLanding v-if="currentSection === 'claw'" />
</div>
@@ -74,6 +75,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import IMChannelPanel from '@/components/IMChannelPanel.vue';
import AgentEmbedChannelPanel from '@/components/AgentEmbedChannelPanel.vue';
import ApiIntegrationSettings from '@/views/integrations/ApiIntegrationSettings.vue';
import ChromeExtensionLanding from '@/views/integrations/ChromeExtensionLanding.vue';
import ClawSkillLanding from '@/views/integrations/ClawSkillLanding.vue';
import { INTEGRATION_PREVIEW_ITEMS, INTEGRATION_TABS, type IntegrationTab } from '@/config/integrations';