Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(frontend): embed OAuth wiring and API integration UI polish
wizardchen146b41193d4a
diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.tsindex b4a96c9cc..eaa9657b5 100644--- a/frontend/src/api/chat/streame.ts+++ b/frontend/src/api/chat/streame.ts@@ -36,7 +36,7 @@ export function useStream() {let renderTimer: number | null = null// 启动流式请求- const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; method: string; url: string; embed_token?: string; embed_session_sig?: string }) => {+ const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {const myGeneration = ++streamGeneration// 重置状态output.value = '';@@ -152,6 +152,7 @@ export function useStream() {"X-Request-ID": requestID,...(!embedToken && tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),...(params.embed_session_sig ? { "X-Embed-Session": params.embed_session_sig } : {}),+ ...(params.embed_visitor_id ? { "X-Embed-Visitor": params.embed_visitor_id } : {}),},body:params.method == "POST"diff --git a/frontend/src/api/embed/index.ts b/frontend/src/api/embed/index.tsindex 494596865..c9adb3995 100644--- a/frontend/src/api/embed/index.ts+++ b/frontend/src/api/embed/index.ts@@ -64,6 +64,30 @@ export const EMBED_SESSION_TOKEN_PREFIX = 'ems_'/** localStorage key prefix for persisted embed chat sessions (per channel). */export const EMBED_CHAT_SESSION_STORAGE_PREFIX = 'weknora-embed-session:'+/** localStorage key prefix for anonymous embed visitor ids (per channel). */+export const EMBED_VISITOR_STORAGE_PREFIX = 'weknora-embed-visitor:'++export function embedVisitorStorageKey(channelId: string): string {+ return `${EMBED_VISITOR_STORAGE_PREFIX}${channelId}`+}++/** Stable anonymous id for this browser on the given channel. */+export function getOrCreateEmbedVisitorId(channelId: string): string {+ if (typeof localStorage === 'undefined' || !channelId) {+ return crypto.randomUUID()+ }+ const key = embedVisitorStorageKey(channelId)+ try {+ const existing = localStorage.getItem(key)?.trim()+ if (existing) return existing+ const id = crypto.randomUUID()+ localStorage.setItem(key, id)+ return id+ } catch {+ return crypto.randomUUID()+ }+}+export function embedChatSessionStorageKey(channelId: string): string {return `${EMBED_CHAT_SESSION_STORAGE_PREFIX}${channelId}`}@@ -197,6 +221,95 @@ export async function stopEmbedSession(return post(`/api/v1/embed/${channelId}/sessions/${sessionId}/stop`, { message_id: messageId }, { headers })}+function embedSessionHeaders(token: string, sessionSig: string, visitorId?: string): Record<string, string> {+ const headers: Record<string, string> = {+ Authorization: `Embed ${token}`,+ 'X-Embed-Session': sessionSig,+ }+ const visitor = visitorId?.trim()+ if (visitor) headers['X-Embed-Visitor'] = visitor+ return headers+}++export async function resolveEmbedMCPOAuth(+ channelId: string,+ token: string,+ sessionId: string,+ sessionSig: string,+ visitorId: string,+ pendingId: string,+ body: { service_id: string; decision?: 'authorize' | 'cancel' },+): Promise<void> {+ await post(+ `/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`,+ body,+ { headers: embedSessionHeaders(token, sessionSig, visitorId) },+ )+}++export async function cancelEmbedMCPOAuth(+ channelId: string,+ token: string,+ sessionId: string,+ sessionSig: string,+ visitorId: string,+ pendingId: string,+): Promise<void> {+ await post(+ `/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}/cancel`,+ {},+ { headers: embedSessionHeaders(token, sessionSig, visitorId) },+ )+}++export async function getEmbedMCPOAuthAuthorizeURL(+ channelId: string,+ token: string,+ sessionId: string,+ sessionSig: string,+ visitorId: string,+ serviceId: string,+ body: { redirect_uri: string; frontend_redirect?: string },+): Promise<string> {+ const response: any = await post(+ `/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/authorize-url`,+ body,+ { headers: embedSessionHeaders(token, sessionSig, visitorId) },+ )+ return (response.data ?? response)?.authorization_url ?? ''+}++export async function getEmbedMCPOAuthStatus(+ channelId: string,+ token: string,+ sessionId: string,+ sessionSig: string,+ visitorId: string,+ serviceId: string,+): Promise<boolean> {+ const response: any = await get(+ `/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/status`,+ { headers: embedSessionHeaders(token, sessionSig, visitorId) },+ )+ return Boolean((response.data ?? response)?.authorized)+}++export async function resolveEmbedToolApproval(+ channelId: string,+ token: string,+ sessionId: string,+ sessionSig: string,+ visitorId: string,+ pendingId: string,+ body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string },+): Promise<void> {+ await post(+ `/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/tool-approvals/${encodeURIComponent(pendingId)}`,+ body,+ { headers: embedSessionHeaders(token, sessionSig, visitorId) },+ )+}+export async function getEmbedMessageList(channelId: string,token: string,diff --git a/frontend/src/composables/useEmbedBridge.ts b/frontend/src/composables/useEmbedBridge.tsindex 733114b68..a46943b7c 100644--- a/frontend/src/composables/useEmbedBridge.ts+++ b/frontend/src/composables/useEmbedBridge.ts@@ -7,6 +7,7 @@ import {exchangeEmbedSession,getEmbedConfig,getEmbedMessageList,+ getOrCreateEmbedVisitorId,isEmbedSessionToken,onEmbedHostContext,onEmbedHostLocale,@@ -85,6 +86,7 @@ export function useEmbedBridge(channelId: Ref<string>) {const config = ref<EmbedChannelPublicConfig | null>(null)const sessionId = ref('')const sessionSig = ref('')+ const visitorId = ref('')const loadError = ref('')const awaitingToken = ref(false)const bootstrapping = ref(false)@@ -109,6 +111,7 @@ export function useEmbedBridge(channelId: Ref<string>) {awaitingToken.value = falsebootstrapping.value = truetoken.value = embedToken+ visitorId.value = getOrCreateEmbedVisitorId(id)try {let apiToken = embedToken@@ -254,6 +257,7 @@ export function useEmbedBridge(channelId: Ref<string>) {config,sessionId,sessionSig,+ visitorId,loadError,awaitingToken,bootstrapping,diff --git a/frontend/src/composables/useEmbedChatSession.ts b/frontend/src/composables/useEmbedChatSession.tsindex 5466a8887..0af2d8e54 100644--- a/frontend/src/composables/useEmbedChatSession.ts+++ b/frontend/src/composables/useEmbedChatSession.ts@@ -25,6 +25,7 @@ import { useStickyBottomOnResize } from '@/composables/useStickyBottomOnResize'export function useEmbedChatSession(options: {sessionId: Ref<string>sessionSig: Ref<string>+ visitorId: Ref<string>channelId: stringtoken: stringagentId: string@@ -315,6 +316,7 @@ export function useEmbedChatSession(options: {url: endpoint,embed_token: options.token,embed_session_sig: options.sessionSig.value,+ embed_visitor_id: options.visitorId.value,})}diff --git a/frontend/src/config/integrations.ts b/frontend/src/config/integrations.tsindex 584f6aff3..1dae3e8f8 100644--- a/frontend/src/config/integrations.ts+++ b/frontend/src/config/integrations.ts@@ -18,7 +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: 'api', icon: { type: 'icon', name: 'server' } },{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },]diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.tsindex 6027da84f..4f516f919 100644--- a/frontend/src/i18n/embed.ts+++ b/frontend/src/i18n/embed.ts@@ -260,11 +260,18 @@ const messages = {"agentStream": {"toolApproval": {"banner": "该 MCP 工具已标记为「需人工审核」,确认参数后再执行",+ "waiting": "等待审核 · {target}",+ "waitingStatus": "等待审核",+ "targetWithTool": "{service} › {tool}",+ "titleWithTarget": "人工审核 · {service} › {tool}",+ "resolvedApproved": "已通过 · {target}",+ "resolvedRejected": "已拒绝 · {target}","service": "服务","tool": "工具","argsLabel": "调用参数","argsModified": "已修改","countdown": "剩余约 {seconds} 秒",+ "countdownShort": "{seconds}s","approve": "通过并执行","reject": "拒绝","approvedTag": "已通过",@@ -274,6 +281,29 @@ const messages = {"submitFailed": "提交失败","userRejected": "用户拒绝"},+ "mcpOAuth": {+ "banner": "该 MCP 服务需要 OAuth 授权后才能调用",+ "waiting": "等待授权 · {target}",+ "waitingStatus": "等待授权",+ "targetWithTool": "{service} › {tool}",+ "titleWithService": "OAuth 授权 · {service}",+ "titleWithTool": "OAuth 授权 · {service} › {tool}",+ "resolvedAuthorized": "已授权 · {target}",+ "resolvedTimedOut": "授权超时 · {target}",+ "resolvedCanceled": "已跳过 · {target}",+ "desc": "点击授权将打开新窗口完成登录,授权成功后会自动继续本次工具调用。",+ "authorize": "去授权",+ "skip": "跳过",+ "countdown": "剩余约 {seconds} 秒",+ "countdownShort": "{seconds}s",+ "authorizedTag": "已授权",+ "timedOutTag": "授权超时",+ "canceledTag": "已取消",+ "authorizedToast": "授权成功,正在继续",+ "startFailed": "发起授权失败",+ "resumeFailed": "恢复执行失败,请重试",+ "skipFailed": "跳过失败,请重试"+ },"tools": {"searchKnowledge": "知识库检索","grepChunks": "搜索关键词",@@ -695,11 +725,18 @@ const messages = {"agentStream": {"toolApproval": {"banner": "This MCP tool requires human approval. Review parameters before execution.",+ "waiting": "Awaiting review · {target}",+ "waitingStatus": "Awaiting review",+ "targetWithTool": "{service} › {tool}",+ "titleWithTarget": "Review · {service} › {tool}",+ "resolvedApproved": "Approved · {target}",+ "resolvedRejected": "Rejected · {target}","service": "Service","tool": "Tool","argsLabel": "Arguments","argsModified": "Modified","countdown": "About {seconds}s remaining",+ "countdownShort": "{seconds}s","approve": "Approve & run","reject": "Reject","approvedTag": "Approved",@@ -709,6 +746,29 @@ const messages = {"submitFailed": "Submit failed","userRejected": "User rejected"},+ "mcpOAuth": {+ "banner": "This MCP service requires OAuth authorization before it can be used",+ "waiting": "Awaiting authorization · {target}",+ "waitingStatus": "Awaiting authorization",+ "targetWithTool": "{service} › {tool}",+ "titleWithService": "OAuth · {service}",+ "titleWithTool": "OAuth · {service} › {tool}",+ "resolvedAuthorized": "Authorized · {target}",+ "resolvedTimedOut": "Timed out · {target}",+ "resolvedCanceled": "Skipped · {target}",+ "desc": "Authorizing opens a new window to sign in. The tool call resumes automatically once authorization succeeds.",+ "authorize": "Authorize",+ "skip": "Skip",+ "countdown": "About {seconds}s remaining",+ "countdownShort": "{seconds}s",+ "authorizedTag": "Authorized",+ "timedOutTag": "Authorization timed out",+ "canceledTag": "Canceled",+ "authorizedToast": "Authorized. Resuming…",+ "startFailed": "Failed to start authorization",+ "resumeFailed": "Failed to resume. Please try again.",+ "skipFailed": "Failed to skip. Please try again."+ },"tools": {"searchKnowledge": "Knowledge Search","grepChunks": "Text Pattern Search",@@ -958,6 +1018,25 @@ const koEmbedPublish = {stopFailed: '중지에 실패했습니다. 다시 시도하세요',},},+ agentStream: {+ mcpOAuth: {+ waiting: '인증 대기 · {target}',+ waitingStatus: '인증 대기',+ targetWithTool: '{service} › {tool}',+ titleWithService: 'OAuth · {service}',+ titleWithTool: 'OAuth · {service} › {tool}',+ authorize: '인증하기',+ skip: '건너뛰기',+ countdownShort: '{seconds}초',+ authorizedTag: '인증됨',+ timedOutTag: '인증 시간 초과',+ canceledTag: '취소됨',+ authorizedToast: '인증 성공, 계속 진행 중',+ startFailed: '인증 시작 실패',+ resumeFailed: '실행 재개 실패, 다시 시도하세요',+ skipFailed: '건너뛰기 실패, 다시 시도하세요',+ },+ },} as constconst ruEmbedPublish = {@@ -1022,6 +1101,25 @@ const ruEmbedPublish = {stopFailed: 'Не удалось остановить. Попробуйте снова.',},},+ agentStream: {+ mcpOAuth: {+ waiting: 'Ожидание авторизации · {target}',+ waitingStatus: 'Ожидание авторизации',+ targetWithTool: '{service} › {tool}',+ titleWithService: 'OAuth · {service}',+ titleWithTool: 'OAuth · {service} › {tool}',+ authorize: 'Авторизовать',+ skip: 'Пропустить',+ countdownShort: '{seconds} с',+ authorizedTag: 'Авторизовано',+ timedOutTag: 'Время авторизации истекло',+ canceledTag: 'Отменено',+ authorizedToast: 'Авторизация успешна, продолжаем',+ startFailed: 'Не удалось начать авторизацию',+ resumeFailed: 'Не удалось возобновить выполнение, повторите попытку',+ skipFailed: 'Не удалось пропустить, повторите попытку',+ },+ },} as constconst SUPPORTED_LOCALES = ['zh-CN', 'en-US', 'ko-KR', 'ru-RU'] as constdiff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex e6783f036..9f9b4911b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -5739,13 +5739,13 @@ export default {tabs: {im: 'IM Integration',embed: 'Web Embed',- api: 'API Key',+ api: 'API Integration',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.',+ title: 'API Integration',+ subtitle: 'Integrate via REST API and configure how requests identify end users.',loading: 'Loading API integration settings...',retry: 'Retry',copy: 'Copy',@@ -5757,9 +5757,9 @@ export default {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. Today this principal only isolates MCP OAuth and related flows; it does not reduce the tenant-admin API scope of the API key.',+ 'Choose how API requests identify the end user. This identity scopes both conversation sessions and MCP tool authorization per user, without reducing the API key\'s tenant-admin access.',principalScope:- 'Principal isolation applies to MCP OAuth tokens and in-chat MCP authorization only. The API key still has tenant-admin API access; knowledge bases, sessions, and other resources are not isolated per external user.',+ 'End-user identity isolates conversation sessions and MCP tool authorization (OAuth) per user. The API key can still access all knowledge bases in the tenant; API permissions are not split per external user.',modeTenant: 'Tenant only',modeDirect: 'Direct user ID',modeSigned: 'Signed token',@@ -5767,13 +5767,25 @@ export default {directWarningDetail:'Anyone with the API key can change the user ID header to impersonate another external user and reuse or hijack that user\'s MCP OAuth authorization. Do not use this from browsers or untrusted clients; use Signed token for end-user apps.',signedRecommended: 'Recommended for user-facing apps: your backend signs a short-lived HS256 JWT for the external user.',+ signedFlowDetail:+ 'Keep the HMAC secret only on WeKnora and your trusted backend—never put it in requests or ship it to browsers. The request header carries the JWT string signed with that secret (it changes on each issuance or after expiry), not the secret itself. JWT must include sub (external user ID), tenant_id, aud=weknora, and exp (max 24h lifetime).',directHeader: 'User ID header',requireDirectHeader: 'Require user ID header',- requireDirectHeaderDesc: 'When enabled, API Key requests without the user ID header are rejected; when disabled they fall back to the tenant principal.',+ requireDirectHeaderDesc:+ 'When enabled, API Key requests without the user ID header are rejected; when disabled, all requests are treated as the whole tenant with no per-user distinction.',tokenHeader: 'Token header',+ tokenHeaderDesc: 'Clients send the backend-signed JWT; header name is configurable.',hmacSecret: 'HMAC secret',+ hmacSecretDesc: 'Same secret stored in WeKnora; used only on your backend to sign JWTs—never send it as a request header.',secretConfigured: 'Secret configured; enter a new value to rotate',generateSecret: 'Generate secret',+ tokenSignExample: 'Backend JWT signing example (Go)',+ signedRequestStep0:+ '# 0. Sign JWT on your backend (HS256, aud=weknora, sub=user id, tenant_id={tenantId}, exp<=24h)',+ signedRequestStep0Hint: '# Put the JWT in {headerName} — not the HMAC secret',+ requestExampleCreateSession: '# 1. Create a session',+ requestExampleAgentChat: '# 2. Agent chat (SSE; replace <session_id> with the id from step 1)',+ requestExampleJwtPlaceholder: '<JWT signed by your backend>',requestExample: 'Request example',loadFailed: 'Failed to load API integration settings',saveFailed: 'Failed to save API integration settings',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex f0fc5771a..3cc55ee19 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -5750,13 +5750,13 @@ export default {tabs: {im: "IM 통합",embed: "웹 임베드",- api: "API Key",+ api: "API 연동",chrome: "Chrome 확장",claw: "Claw Skill",},api: {- title: "API Key 통합",- subtitle: "테넌트 API Key로 서버 연동을 구성하고, API 요청이 최종 사용자 ID를 전달하는 방식을 선택합니다.",+ title: "API 연동",+ subtitle: "REST API로 서비스를 연동하고, 요청이 최종 사용자를 식별하는 방식을 설정합니다.",loading: "API 통합 설정을 불러오는 중...",retry: "다시 시도",copy: "복사",@@ -5768,23 +5768,35 @@ export default {apiKeyDesc: "API Key는 계속 테넌트 단위입니다. 사용자 ID는 아래 모드로 전달합니다.",principalMode: "사용자 ID 모드",principalModeDesc:- "X-API-Key 요청을 Principal로 매핑하는 방식입니다. 현재 Principal은 MCP OAuth 등 사용자별 기능만 분리하며, API Key의 테넌트 관리자 권한은 줄이지 않습니다.",+ "API 요청이 최종 사용자를 어떻게 식별할지 설정합니다. 이 신원은 대화 Session과 MCP 도구 인증을 사용자별로 구분하며, API Key의 테넌트 관리자 권한은 바뀌지 않습니다.",principalScope:- "Principal 분리는 MCP OAuth 토큰과 대화 내 MCP 인증에만 적용됩니다. API Key는 여전히 테넌트 관리자 API 권한을 가지며, 지식베이스·세션 등은 외부 사용자별로 분리되지 않습니다.",+ "최종 사용자별로 대화 Session과 MCP 도구 인증(OAuth)을 구분합니다. API Key는 여전히 테넌트 내 모든 지식베이스에 접근할 수 있으며, API 권한 범위는 외부 사용자별로 나뉘지 않습니다.",modeTenant: "테넌트만",modeDirect: "사용자 ID 직접 전달",modeSigned: "서명 토큰",directWarning: "직접 사용자 ID 모드는 요청 헤더를 신뢰합니다. 신뢰된 서버 간 호출에만 사용하세요.",directWarningDetail:"API Key를 가진 호출자는 사용자 ID 헤더를 바꿔 다른 외부 사용자를 가장하고 해당 사용자의 MCP OAuth 인증을 공유하거나 탈취할 수 있습니다. 브라우저나 신뢰할 수 없는 클라이언트에는 사용하지 마세요. 최종 사용자 앱에는 서명 토큰을 사용하세요.",- signedRecommended: "사용자 대상 앱에는 권장됩니다. 비즈니스 백엔드가 외부 사용자용 단기 HS256 JWT를 서명합니다.",+ signedRecommended: "사용자 대상 앱에 권장: 비즈니스 백엔드가 외부 사용자용 단기 HS256 JWT를 서명합니다.",+ signedFlowDetail:+ "HMAC secret은 WeKnora와 신뢰할 수 있는 백엔드에만 보관하세요. 요청에 넣거나 브라우저에 배포하지 마세요. 요청 헤더에는 secret이 아니라 해당 secret으로 서명한 JWT 문자열을 넣습니다(발급마다 또는 만료 후 변경). JWT에는 sub(외부 사용자 ID), tenant_id, aud=weknora, exp(최대 24시간)가 필요합니다.",directHeader: "사용자 ID 헤더",requireDirectHeader: "사용자 ID 헤더 필수",- requireDirectHeaderDesc: "켜면 사용자 ID 헤더가 없는 API Key 요청을 거부하고, 끄면 테넌트 Principal로 처리합니다.",+ requireDirectHeaderDesc:+ "켜면 사용자 ID 헤더가 없는 API Key 요청을 거부하고, 끄면 테넌트 전체로 통일 처리하며 개별 사용자를 구분하지 않습니다.",tokenHeader: "토큰 헤더",+ tokenHeaderDesc: "클라이언트는 백엔드가 서명한 JWT를 전달합니다. 헤더 이름은 변경할 수 있습니다.",hmacSecret: "HMAC secret",+ hmacSecretDesc: "WeKnora에 저장된 것과 동일한 secret. 백엔드에서 JWT 서명에만 사용하며 요청 헤더로 보내지 않습니다.",secretConfigured: "Secret configured; enter a new value to rotate",generateSecret: "Secret 생성",+ tokenSignExample: "백엔드 JWT 서명 예시 (Go)",+ signedRequestStep0:+ "# 0. 백엔드에서 JWT 서명 (HS256, aud=weknora, sub=사용자 ID, tenant_id={tenantId}, exp 최대 24시간)",+ signedRequestStep0Hint: "# JWT를 {headerName} 헤더에 넣고 HMAC secret은 보내지 마세요",+ requestExampleCreateSession: "# 1. 세션 생성",+ requestExampleAgentChat: "# 2. Agent 대화 (SSE; <session_id>를 1단계 id로 교체)",+ requestExampleJwtPlaceholder: "<백엔드가 서명한 JWT>",requestExample: "요청 예시",loadFailed: "API 통합 설정을 불러오지 못했습니다",saveFailed: "API 통합 설정 저장 실패",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 8f482e49e..cd63b374f 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -5572,13 +5572,13 @@ export default {tabs: {im: 'IM-интеграция',embed: 'Веб-встраивание',- api: 'API Key',+ api: 'API-интеграция',chrome: 'Расширение Chrome',claw: 'Claw Skill',},api: {- title: 'Интеграция API Key',- subtitle: 'Используйте API Key арендатора для серверной интеграции и выберите, как передавать идентификатор конечного пользователя.',+ title: 'API-интеграция',+ subtitle: 'Подключайте сервис через REST API и настройте идентификацию конечного пользователя в запросах.',loading: 'Загрузка настроек API-интеграции...',retry: 'Повторить',copy: 'Копировать',@@ -5590,9 +5590,9 @@ export default {apiKeyDesc: 'API Key остаётся на уровне арендатора; идентификатор пользователя задаётся режимом ниже.',principalMode: 'Режим идентификации пользователя',principalModeDesc:- 'Определяет, как запросы с X-API-Key сопоставляются с Principal. Сейчас Principal изолирует только MCP OAuth и связанные потоки и не сужает область API ключа уровня admin арендатора.',+ 'Настройка того, как API-запросы идентифицируют конечного пользователя. Эта идентичность разделяет сессии диалога и авторизацию MCP-инструментов по пользователям, не сужая доступ API key уровня admin арендатора.',principalScope:- 'Изоляция Principal распространяется только на токены MCP OAuth и авторизацию MCP в чате. API key по-прежнему имеет доступ admin арендатора; базы знаний, сессии и другие ресурсы не изолируются по внешнему пользователю.',+ 'Идентификация конечного пользователя разделяет сессии диалога и авторизацию MCP-инструментов (OAuth) по пользователям. API key по-прежнему имеет доступ ко всем базам знаний арендатора; область API-прав не делится по внешним пользователям.',modeTenant: 'Только арендатор',modeDirect: 'Прямой ID пользователя',modeSigned: 'Подписанный token',@@ -5600,13 +5600,25 @@ export default {directWarningDetail:'Любой, у кого есть API key, может подменить заголовок ID пользователя, выдать себя за другого внешнего пользователя и переиспользовать или перехватить его авторизацию MCP OAuth. Не используйте в браузере или ненадёжных клиентах; для пользовательских приложений выбирайте подписанный token.',signedRecommended: 'Рекомендуется для пользовательских приложений: ваш backend подписывает краткоживущий HS256 JWT для внешнего пользователя.',+ signedFlowDetail:+ 'HMAC secret храните только в WeKnora и на доверенном backend — не передавайте в запросах и не отдавайте браузеру. В заголовке запроса передаётся JWT, подписанный этим secret (меняется при каждой выдаче или после истечения), а не сам secret. JWT должен содержать sub (ID внешнего пользователя), tenant_id, aud=weknora и exp (не более 24 ч).',directHeader: 'Заголовок ID пользователя',requireDirectHeader: 'Требовать заголовок ID пользователя',- requireDirectHeaderDesc: 'Если включено, запросы без заголовка ID пользователя отклоняются; иначе используется Principal уровня арендатора.',+ requireDirectHeaderDesc:+ 'Если включено, запросы без заголовка ID пользователя отклоняются; иначе все запросы обрабатываются как единый арендатор без различия конечных пользователей.',tokenHeader: 'Заголовок token',+ tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend; имя заголовка настраивается.',hmacSecret: 'HMAC secret',+ hmacSecretDesc: 'Тот же secret, что в WeKnora; только для подписи JWT на backend — не отправляйте его в заголовке запроса.',secretConfigured: 'Secret настроен; введите новое значение для ротации',generateSecret: 'Сгенерировать secret',+ tokenSignExample: 'Пример подписи JWT на backend (Go)',+ signedRequestStep0:+ '# 0. Подпишите JWT на backend (HS256, aud=weknora, sub=ID пользователя, tenant_id={tenantId}, exp не более 24 ч)',+ signedRequestStep0Hint: '# Передайте JWT в заголовке {headerName}, не отправляйте HMAC secret',+ requestExampleCreateSession: '# 1. Создать session',+ requestExampleAgentChat: '# 2. Agent-чат (SSE; замените <session_id> на id из шага 1)',+ requestExampleJwtPlaceholder: '<JWT, подписанный backend>',requestExample: 'Пример запроса',loadFailed: 'Не удалось загрузить настройки API-интеграции',saveFailed: 'Не удалось сохранить настройки API-интеграции',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 4d91ec7c2..d7b35f3e1 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -5752,13 +5752,13 @@ export default {tabs: {im: "IM 集成",embed: "网页嵌入",- api: "API Key",+ api: "API 集成",chrome: "Chrome 插件",claw: "Claw Skill",},api: {- title: "API Key 集成",- subtitle: "使用租户级 API Key 接入服务,并选择 API 请求如何携带终端用户身份。",+ title: "API 集成",+ subtitle: "通过 REST API 接入服务,并配置请求如何携带终端用户身份。",loading: "正在加载 API 集成设置...",retry: "重试",copy: "复制",@@ -5769,23 +5769,36 @@ export default {apiKey: "租户 API Key",apiKeyDesc: "API Key 仍按租户级管理;终端用户身份由下方模式提供。",principalMode: "用户身份模式",- principalModeDesc: "决定 X-API-Key 请求如何映射为 Principal。当前 Principal 仅用于按用户隔离 MCP OAuth 等能力,不会缩小 API Key 的租户管理员权限。",+ principalModeDesc:+ "配置 API 请求如何识别终端用户。该身份会同时用于区分不同用户的对话 Session 与 MCP 工具授权,不会改变 API Key 的租户管理员权限。",principalScope:- "Principal 仅隔离 MCP OAuth 令牌与对话内 MCP 授权;API Key 仍拥有租户内管理员级 API 权限,知识库、会话等资源不会按外部用户隔离。",+ "按终端用户隔离对话 Session 与 MCP 工具授权(OAuth);API Key 仍可访问租户内全部知识库等资源,权限范围不按外部用户拆分。",modeTenant: "仅租户",modeDirect: "直接传用户 ID",modeSigned: "签名 Token",directWarning: "直接传用户 ID 会信任调用方请求头,仅适用于可信服务端到服务端调用。",directWarningDetail:"任何持有 API Key 的调用方都可以通过修改用户 ID 请求头冒充其他外部用户,从而共用或劫持其 MCP OAuth 授权。请勿用于浏览器或不可信客户端;面向终端用户请使用「签名 Token」。",- signedRecommended: "推荐给面向用户的应用:业务方后端为外部用户签发短期 HS256 JWT。",+ signedRecommended: "推荐给面向用户的应用:由你的业务后端为外部用户签发短期 HS256 JWT。",+ signedFlowDetail:+ "HMAC 密钥仅保存在 WeKnora 与你的可信后端,切勿放入请求或下发给浏览器。请求头里传的是用该密钥签出的 JWT 字符串(每次签发或过期后会变),不是密钥本身。JWT 须包含 sub(外部用户 ID)、tenant_id、aud=weknora、exp(有效期不超过 24 小时)。",directHeader: "用户 ID 请求头",requireDirectHeader: "必须携带用户 ID",- requireDirectHeaderDesc: "开启后,缺少用户 ID 请求头的 API Key 请求将被拒绝;关闭则回退为租户级 Principal。",+ requireDirectHeaderDesc:+ "开启后,缺少用户 ID 请求头的 API Key 请求将被拒绝;关闭则按整个租户统一处理,不区分具体终端用户。",tokenHeader: "Token 请求头",+ tokenHeaderDesc: "客户端携带后端签发的 JWT,请求头名可自定义。",hmacSecret: "HMAC 密钥",+ hmacSecretDesc: "与 WeKnora 保存的同一份密钥;仅用于后端签发 JWT,不要作为请求头发送。",secretConfigured: "已配置密钥;输入新值可轮换",generateSecret: "生成密钥",+ tokenSignExample: "后端签发 JWT 示例(Go)",+ signedRequestStep0:+ "# 0. 在你的后端签发 JWT(HS256,aud=weknora,sub=用户 ID,tenant_id={tenantId},exp 不超过 24 小时)",+ signedRequestStep0Hint: "# 将 JWT 放入 {headerName} 请求头,不要传 HMAC 密钥",+ requestExampleCreateSession: "# 1. 创建会话",+ requestExampleAgentChat: "# 2. Agent 对话(SSE;将 <session_id> 替换为第 1 步返回的 id)",+ requestExampleJwtPlaceholder: "<后端签发的 JWT>",requestExample: "请求示例",loadFailed: "加载 API 集成设置失败",saveFailed: "保存 API 集成设置失败",diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex debe93c2e..06bf5b125 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -85,7 +85,7 @@:mcp-tool-name="event.mcp_tool_name || ''" :description="event.description":args-json="event.args_json" :timeout-seconds="event.timeout_seconds":requested-at="event.requested_at" :resolved="event.resolved" :approved="event.approved"- :resolve-reason="event.resolve_reason" />+ :resolve-reason="event.resolve_reason" v-bind="embedAuthProps" /></div><!-- MCP OAuth in-conversation authorization prompt -->@@ -94,7 +94,8 @@:service-name="event.service_name || ''" :mcp-tool-name="event.mcp_tool_name || ''":timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at":resolved="event.resolved" :authorized="event.authorized"- :resolve-reason="event.resolve_reason" :timed-out="event.timed_out" :canceled="event.canceled" />+ :resolve-reason="event.resolve_reason" :timed-out="event.timed_out" :canceled="event.canceled"+ v-bind="embedAuthProps" /></div><!-- Tool Call Event (non-thinking) -->@@ -240,7 +241,7 @@<ToolApprovalCard :pending-id="event.pending_id" :service-name="event.service_name || ''":mcp-tool-name="event.mcp_tool_name || ''" :description="event.description" :args-json="event.args_json":timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at" :resolved="event.resolved"- :approved="event.approved" :resolve-reason="event.resolve_reason" />+ :approved="event.approved" :resolve-reason="event.resolve_reason" v-bind="embedAuthProps" /></div><!-- MCP OAuth in-conversation authorization prompt -->@@ -249,7 +250,7 @@:service-name="event.service_name || ''" :mcp-tool-name="event.mcp_tool_name || ''":timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at" :resolved="event.resolved":authorized="event.authorized" :resolve-reason="event.resolve_reason" :timed-out="event.timed_out"- :canceled="event.canceled" />+ :canceled="event.canceled" v-bind="embedAuthProps" /></div><!-- Thinking Tool Call -->@@ -727,9 +728,20 @@ const props = defineProps<{embeddedMode?: boolean;embedChannelId?: string;embedToken?: string;+ embedSessionSig?: string;+ embedVisitorId?: string;ragMode?: boolean;}>();+const embedAuthProps = computed(() => ({+ embeddedMode: props.embeddedMode,+ embedChannelId: props.embedChannelId,+ embedToken: props.embedToken,+ embedSessionId: props.sessionId,+ embedSessionSig: props.embedSessionSig,+ embedVisitorId: props.embedVisitorId,+}));+const showRequestInfo = computed(() => !props.embeddedMode && !!(props.session?.request_id || props.session?.id),);diff --git a/frontend/src/views/chat/components/McpOAuthCard.vue b/frontend/src/views/chat/components/McpOAuthCard.vueindex 384fa2d40..1ece3bb0b 100644--- a/frontend/src/views/chat/components/McpOAuthCard.vue+++ b/frontend/src/views/chat/components/McpOAuthCard.vue@@ -41,6 +41,12 @@ import {resolveMCPOAuth,MCP_OAUTH_CALLBACK_PATH,} from '@/api/mcp-service'+import {+ cancelEmbedMCPOAuth,+ getEmbedMCPOAuthAuthorizeURL,+ getEmbedMCPOAuthStatus,+ resolveEmbedMCPOAuth,+} from '@/api/embed'const props = defineProps<{pendingId: string@@ -54,8 +60,22 @@ const props = defineProps<{resolveReason?: stringtimedOut?: booleancanceled?: boolean+ embeddedMode?: boolean+ embedChannelId?: string+ embedToken?: string+ embedSessionId?: string+ embedSessionSig?: string+ embedVisitorId?: string}>()+const useEmbedOAuth = () =>+ props.embeddedMode+ && props.embedChannelId+ && props.embedToken+ && props.embedSessionId+ && props.embedSessionSig+ && props.embedVisitorId+const { t } = useI18n()const authorizing = ref(false)@@ -127,7 +147,18 @@ const skip = async () => {if (props.resolved || canceling.value) returncanceling.value = truetry {- await cancelMCPOAuth(props.pendingId)+ if (useEmbedOAuth()) {+ await cancelEmbedMCPOAuth(+ props.embedChannelId!,+ props.embedToken!,+ props.embedSessionId!,+ props.embedSessionSig!,+ props.embedVisitorId!,+ props.pendingId,+ )+ } else {+ await cancelMCPOAuth(props.pendingId)+ }} catch (e: any) {const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.skipFailed')MessagePlugin.error(msg)@@ -141,11 +172,23 @@ const authorize = async () => {authorizing.value = truetry {const redirectUri = window.location.origin + MCP_OAUTH_CALLBACK_PATH- const frontendRedirect = window.location.origin + '/'- const authUrl = await getMCPOAuthAuthorizeURL(props.serviceId, {- redirect_uri: redirectUri,- frontend_redirect: frontendRedirect,- })+ const frontendRedirect = useEmbedOAuth()+ ? window.location.origin + window.location.pathname + window.location.search+ : window.location.origin + '/'+ const authUrl = useEmbedOAuth()+ ? await getEmbedMCPOAuthAuthorizeURL(+ props.embedChannelId!,+ props.embedToken!,+ props.embedSessionId!,+ props.embedSessionSig!,+ props.embedVisitorId!,+ props.serviceId,+ { redirect_uri: redirectUri, frontend_redirect: frontendRedirect },+ )+ : await getMCPOAuthAuthorizeURL(props.serviceId, {+ redirect_uri: redirectUri,+ frontend_redirect: frontendRedirect,+ })if (!authUrl) {MessagePlugin.error(t('agentStream.mcpOAuth.startFailed'))authorizing.value = false@@ -156,7 +199,16 @@ const authorize = async () => {const closed = !popup || popup.closedlet ok = falsetry {- ok = await getMCPOAuthStatus(props.serviceId)+ ok = useEmbedOAuth()+ ? await getEmbedMCPOAuthStatus(+ props.embedChannelId!,+ props.embedToken!,+ props.embedSessionId!,+ props.embedSessionSig!,+ props.embedVisitorId!,+ props.serviceId,+ )+ : await getMCPOAuthStatus(props.serviceId)} catch {/* transient; keep polling */}@@ -164,7 +216,19 @@ const authorize = async () => {stopPoll()try { popup?.close() } catch { /* cross-origin close may throw */ }try {- await resolveMCPOAuth(props.pendingId, { service_id: props.serviceId, decision: 'authorize' })+ if (useEmbedOAuth()) {+ await resolveEmbedMCPOAuth(+ props.embedChannelId!,+ props.embedToken!,+ props.embedSessionId!,+ props.embedSessionSig!,+ props.embedVisitorId!,+ props.pendingId,+ { service_id: props.serviceId, decision: 'authorize' },+ )+ } else {+ await resolveMCPOAuth(props.pendingId, { service_id: props.serviceId, decision: 'authorize' })+ }MessagePlugin.success(t('agentStream.mcpOAuth.authorizedToast'))} catch (e: any) {const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.resumeFailed')diff --git a/frontend/src/views/chat/components/ToolApprovalCard.vue b/frontend/src/views/chat/components/ToolApprovalCard.vueindex 94de27a45..e1d3d498c 100644--- a/frontend/src/views/chat/components/ToolApprovalCard.vue+++ b/frontend/src/views/chat/components/ToolApprovalCard.vue@@ -74,6 +74,7 @@ import { ref, computed, onMounted, onBeforeUnmount } from 'vue'import { MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import { resolveToolApproval } from '@/api/mcp-service'+import { resolveEmbedToolApproval } from '@/api/embed'const props = defineProps<{pendingId: string@@ -86,8 +87,22 @@ const props = defineProps<{resolved?: booleanapproved?: booleanresolveReason?: string+ embeddedMode?: boolean+ embedChannelId?: string+ embedToken?: string+ embedSessionId?: string+ embedSessionSig?: string+ embedVisitorId?: string}>()+const useEmbedApproval = () =>+ props.embeddedMode+ && props.embedChannelId+ && props.embedToken+ && props.embedSessionId+ && props.embedSessionSig+ && props.embedVisitorId+const { t } = useI18n()function formatJson(raw: string): string {@@ -200,11 +215,25 @@ const submit = async (decision: 'approve' | 'reject') => {return}}- await resolveToolApproval(props.pendingId, {- decision,- modified_args: decision === 'approve' ? modified : undefined,- reason: decision === 'reject' ? t('agentStream.toolApproval.userRejected') : undefined,- })+ await (useEmbedApproval()+ ? resolveEmbedToolApproval(+ props.embedChannelId!,+ props.embedToken!,+ props.embedSessionId!,+ props.embedSessionSig!,+ props.embedVisitorId!,+ props.pendingId,+ {+ decision,+ modified_args: decision === 'approve' ? modified : undefined,+ reason: decision === 'reject' ? t('agentStream.toolApproval.userRejected') : undefined,+ },+ )+ : resolveToolApproval(props.pendingId, {+ decision,+ modified_args: decision === 'approve' ? modified : undefined,+ reason: decision === 'reject' ? t('agentStream.toolApproval.userRejected') : undefined,+ }))MessagePlugin.success(t('agentStream.toolApproval.submitted'))} catch (e: any) {const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.toolApproval.submitFailed')diff --git a/frontend/src/views/embed/EmbedBotMessage.vue b/frontend/src/views/embed/EmbedBotMessage.vueindex 9e7b05433..843fe4dc6 100644--- a/frontend/src/views/embed/EmbedBotMessage.vue+++ b/frontend/src/views/embed/EmbedBotMessage.vue@@ -3,12 +3,14 @@<div v-if="session?.isRagMode" class="rag-answer-stack"><RagPipelineProgress :session="session" embedded-mode /><AgentStreamDisplay v-if="session?.isAgentMode" :session="session" :session-id="sessionId" :user-query="userQuery"- rag-mode :embedded-mode="embeddedMode" :embed-channel-id="embedChannelId" :embed-token="embedToken" />+ rag-mode :embedded-mode="embeddedMode" :embed-channel-id="embedChannelId" :embed-token="embedToken"+ :embed-session-sig="embedSessionSig" :embed-visitor-id="embedVisitorId" /></div><template v-else><DocInfo v-if="session?.knowledge_references?.length" :session="session" embedded-mode /><AgentStreamDisplay v-if="session?.isAgentMode" :session="session" :session-id="sessionId" :user-query="userQuery"- :embedded-mode="embeddedMode" :embed-channel-id="embedChannelId" :embed-token="embedToken" />+ :embedded-mode="embeddedMode" :embed-channel-id="embedChannelId" :embed-token="embedToken"+ :embed-session-sig="embedSessionSig" :embed-visitor-id="embedVisitorId" /></template><DeepThink v-if="session?.showThink && !session?.isAgentMode" :deep-session="session" /><div v-if="!session?.hideContent && !session?.isAgentMode" ref="parentMd">@@ -107,6 +109,8 @@ const props = withDefaults(embeddedMode?: booleanembedChannelId?: stringembedToken?: string+ embedSessionSig?: string+ embedVisitorId?: string}>(),{content: '',@@ -116,6 +120,8 @@ const props = withDefaults(embeddedMode: true,embedChannelId: '',embedToken: '',+ embedSessionSig: '',+ embedVisitorId: '',},)diff --git a/frontend/src/views/embed/EmbedChatCore.vue b/frontend/src/views/embed/EmbedChatCore.vueindex c12405652..36e4c1974 100644--- a/frontend/src/views/embed/EmbedChatCore.vue+++ b/frontend/src/views/embed/EmbedChatCore.vue@@ -66,6 +66,8 @@:embedded-mode="true":embed-channel-id="channelId":embed-token="token"+ :embed-session-sig="sessionSig"+ :embed-visitor-id="visitorId"/></div></div>@@ -113,6 +115,7 @@ import { useEmbedChatSession } from '@/composables/useEmbedChatSession'const props = defineProps<{sessionId: stringsessionSig: string+ visitorId: stringchannelId: stringtoken: stringagentId: string@@ -135,6 +138,7 @@ const emit = defineEmits<{const { t } = useI18n()const sessionIdRef = toRef(props, 'sessionId')const sessionSigRef = toRef(props, 'sessionSig')+const visitorIdRef = toRef(props, 'visitorId')const suggestedQuestions = ref<SuggestedQuestion[]>([])const suggestedLoading = ref(false)const hostContextRef = ref<Record<string, unknown>>(props.hostContext || {})@@ -189,6 +193,7 @@ const {} = useEmbedChatSession({sessionId: sessionIdRef,sessionSig: sessionSigRef,+ visitorId: visitorIdRef,channelId: props.channelId,token: props.token,agentId: props.agentId,diff --git a/frontend/src/views/embed/EmbedChatView.vue b/frontend/src/views/embed/EmbedChatView.vueindex b6b819b33..cf769b93e 100644--- a/frontend/src/views/embed/EmbedChatView.vue+++ b/frontend/src/views/embed/EmbedChatView.vue@@ -2,6 +2,7 @@<EmbedChatCore:session-id="sessionId":session-sig="sessionSig"+ :visitor-id="visitorId":channel-id="channelId":token="token":agent-id="agentId"@@ -27,6 +28,7 @@ const EmbedChatCore = defineAsyncComponent(() => import('@/views/embed/EmbedChatdefineProps<{sessionId: stringsessionSig: string+ visitorId: stringchannelId: stringtoken: stringagentId: stringdiff --git a/frontend/src/views/embed/EmbedPage.vue b/frontend/src/views/embed/EmbedPage.vueindex 0f47dc228..027e2f6c0 100644--- a/frontend/src/views/embed/EmbedPage.vue+++ b/frontend/src/views/embed/EmbedPage.vue@@ -29,6 +29,7 @@v-if="sessionId":session-id="sessionId":session-sig="sessionSig"+ :visitor-id="visitorId":channel-id="channelId":token="token":agent-id="config.agent_id"@@ -69,6 +70,7 @@ const {config,sessionId,sessionSig,+ visitorId,loadError,awaitingToken,bootstrapping,diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vueindex 8439aa80f..b312b508d 100644--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue@@ -1,10 +1,5 @@<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 class="api-integration"><div v-if="loading" class="state-row"><t-loading size="small" /><span>{{ $t('integrations.api.loading') }}</span>@@ -48,46 +43,53 @@</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-alert theme="info" :message="$t('integrations.api.principalScope')" />-- <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"- >- <template #message>{{ $t('integrations.api.directWarning') }}</template>- {{ $t('integrations.api.directWarningDetail') }}- </t-alert>- <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>+ <section class="settings-band principal-section">+ <div class="principal-section__header">+ <label>{{ $t('integrations.api.principalMode') }}</label>+ <p>{{ $t('integrations.api.principalModeDesc') }}</p>+ <p class="principal-section__scope">{{ $t('integrations.api.principalScope') }}</p>+ </div>++ <t-radio-group v-model="form.mode" class="mode-radio">+ <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>++ <div v-if="form.mode !== 'tenant'" class="mode-detail">+ <t-alert+ v-if="form.mode === 'direct_header'"+ theme="warning"+ :title="$t('integrations.api.directWarning')"+ :message="$t('integrations.api.directWarningDetail')"+ />+ <p v-else-if="form.mode === 'signed_token'" class="mode-hint">+ <span class="mode-hint__title">{{ $t('integrations.api.signedRecommended') }}</span>+ {{ $t('integrations.api.signedFlowDetail') }}+ </p>++ <div v-if="form.mode === 'direct_header'" class="form-grid">+ <div class="form-item">+ <label class="form-item__label">{{ $t('integrations.api.directHeader') }}</label><t-input v-model="form.direct_header_name" class="mono-input" />- <label>{{ $t('integrations.api.requireDirectHeader') }}</label>- <t-switch v-model="form.require_direct_header" />- <p class="field-hint span-all">{{ $t('integrations.api.requireDirectHeaderDesc') }}</p></div>+ <div class="form-item form-item--switch">+ <label class="form-item__label">{{ $t('integrations.api.requireDirectHeader') }}</label>+ <div class="form-item__control">+ <t-switch v-model="form.require_direct_header" size="small" />+ <span class="form-item__hint">{{ $t('integrations.api.requireDirectHeaderDesc') }}</span>+ </div>+ </div>+ </div>- <div v-if="form.mode === 'signed_token'" class="field-grid">- <label>{{ $t('integrations.api.tokenHeader') }}</label>+ <div v-else-if="form.mode === 'signed_token'" class="form-grid">+ <div class="form-item">+ <label class="form-item__label">{{ $t('integrations.api.tokenHeader') }}</label><t-input v-model="form.signed_token_header_name" class="mono-input" />- <label>{{ $t('integrations.api.hmacSecret') }}</label>+ <p class="form-item__hint">{{ $t('integrations.api.tokenHeaderDesc') }}</p>+ </div>+ <div class="form-item">+ <label class="form-item__label">{{ $t('integrations.api.hmacSecret') }}</label><div class="copy-field"><t-inputv-model="secretInput"@@ -99,27 +101,44 @@<t-icon name="refresh" /></t-button></div>+ <p class="form-item__hint">{{ $t('integrations.api.hmacSecretDesc') }}</p></div>+ </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') }}+ <div class="examples">+ <t-tabs+ v-if="form.mode === 'signed_token'"+ v-model="exampleTab"+ class="snippet-tabs"+ >+ <t-tab-panel value="jwt" :label="$t('integrations.api.tokenSignExample')" />+ <t-tab-panel value="curl" :label="$t('integrations.api.requestExample')" />+ </t-tabs>+ <div class="code-panel">+ <div class="code-panel__toolbar">+ <span class="code-panel__label">{{ activeExampleLabel }}</span>+ <t-button size="small" variant="text" class="code-panel__copy" @click="copy(activeExampleText)">+ <template #icon><t-icon name="file-copy" /></template>+ {{ $t('integrations.api.copy') }}</t-button></div>+ <pre class="code-panel__pre">{{ activeExampleText }}</pre></div></div>++ <div class="actions">+ <t-button theme="primary" :loading="saving" :disabled="!canSave" @click="save">+ {{ $t('integrations.api.save') }}+ </t-button>+ </div></section></div></div></template><script setup lang="ts">-import { computed, onMounted, reactive, ref } from 'vue'+import { computed, onMounted, reactive, ref, watch } from 'vue'import { MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import { getCurrentUser } from '@/api/auth'@@ -141,6 +160,7 @@ const apiKey = ref('')const showApiKey = ref(false)const config = ref<APIPrincipalConfig | null>(null)const secretInput = ref('')+const exampleTab = ref<'jwt' | 'curl'>('curl')const form = reactive({mode: 'tenant' as APIPrincipalMode,@@ -149,6 +169,12 @@ const form = reactive({require_direct_header: false,})+watch(() => form.mode, (mode) => {+ if (mode === 'signed_token') {+ exampleTab.value = 'curl'+ }+})+const apiBaseUrl = computed(() => {const configured = getApiBaseUrl().trim().replace(/\/$/, '')const origin = typeof window !== 'undefined' && window.location.origin !== 'null' ? window.location.origin : ''@@ -169,22 +195,78 @@ const canSave = computed(() => {return true})+const tokenSignExample = computed(() => {+ const tid = tenantId.value || 10000+ const headerName = form.signed_token_header_name.trim() || 'X-External-User-Token'+ return `import (+ "time"++ "github.com/golang-jwt/jwt/v5"+)++func signExternalUserToken(hmacSecret, externalUserID string, tenantID uint64) (string, error) {+ claims := jwt.MapClaims{+ "sub": externalUserID, // e.g. "user_123"+ "tenant_id": float64(tenantID),+ "aud": "weknora",+ "exp": time.Now().Add(time.Hour).Unix(),+ }+ return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).+ SignedString([]byte(hmacSecret))+}++// Send on each WeKnora API request:+// ${headerName}: <JWT from signExternalUserToken>+// Tenant ID for this workspace: ${tid}`+})+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"`,- ]+ const apiKeyHeader = ` -H "X-API-Key: ${apiKey.value ? '<API_KEY>' : '<YOUR_API_KEY>'}"`+ const contentType = ' -H "Content-Type: application/json"'+ const principalHeaders: string[] = []+ const tokenHeaderName = form.signed_token_header_name.trim() || 'X-External-User-Token'if (form.mode === 'direct_header') {- lines.push(` -H "${form.direct_header_name || 'X-External-User-ID'}: user_123"`)+ principalHeaders.push(` -H "${form.direct_header_name || 'X-External-User-ID'}: user_123"`)+ }+ if (form.mode === 'signed_token') {+ principalHeaders.push(` -H "${tokenHeaderName}: ${t('integrations.api.requestExampleJwtPlaceholder')}"`)}+ const commonHeaders = [apiKeyHeader, contentType, ...principalHeaders].join(' \\\n')++ const lines: string[] = []if (form.mode === 'signed_token') {- lines.push(` -H "${form.signed_token_header_name || 'X-External-User-Token'}: <HS256_JWT>"`)+ lines.push(+ t('integrations.api.signedRequestStep0', { tenantId: tenantId.value || '<tenant_id>' }),+ t('integrations.api.signedRequestStep0Hint', { headerName: tokenHeaderName }),+ '',+ )}- lines.push(` -d '{"query":"hello"}'`)- return lines.join(' \\\n')+ lines.push(+ t('integrations.api.requestExampleCreateSession'),+ `curl -X POST ${apiBaseUrl.value}/sessions \\`,+ commonHeaders,+ ` -d '{}'`,+ '',+ t('integrations.api.requestExampleAgentChat'),+ `curl -N -X POST ${apiBaseUrl.value}/agent-chat/<session_id> \\`,+ commonHeaders,+ ` -d '{"query":"hello"}'`,+ )+ return lines.join('\n')})+const activeExampleText = computed(() => (+ form.mode === 'signed_token' && exampleTab.value === 'jwt'+ ? tokenSignExample.value+ : requestExample.value+))++const activeExampleLabel = computed(() => (+ form.mode === 'signed_token' && exampleTab.value === 'jwt'+ ? t('integrations.api.tokenSignExample')+ : t('integrations.api.requestExample')+))+async function load() {loading.value = trueerror.value = ''@@ -288,14 +370,17 @@ onMounted(load)border-bottom: 1px solid var(--td-component-stroke);}-.row--stack {- grid-template-columns: minmax(220px, 0.8fr) minmax(420px, 1fr);+.principal-section {+ display: flex;+ flex-direction: column;+ gap: 20px;+ padding: 20px 0;}-.row-info {+.principal-section__header {label {display: block;- margin-bottom: 4px;+ margin-bottom: 6px;color: var(--td-text-color-primary);font-size: 15px;font-weight: 600;@@ -305,71 +390,167 @@ onMounted(load)margin: 0;color: var(--td-text-color-secondary);font-size: 13px;- line-height: 1.5;+ line-height: 1.55;}}-.row-control,-.copy-field {+.principal-section__scope {+ margin-top: 6px !important;+ color: var(--td-text-color-placeholder) !important;+ font-size: 12px !important;+}++.mode-radio {+ width: fit-content;+ max-width: 100%;+}++.mode-detail {display: flex;- align-items: center;- gap: 8px;- min-width: 0;+ flex-direction: column;+ gap: 16px;+ width: 100%;+ max-width: 640px;+}++.mode-hint {+ margin: 0;+ padding: 10px 12px;+ border-radius: 8px;+ border: 1px solid var(--td-component-stroke);+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-size: 13px;+ line-height: 1.55;++ &__title {+ display: block;+ margin-bottom: 4px;+ color: var(--td-text-color-primary);+ font-weight: 500;+ }}-.mode-panel {+.form-grid {display: flex;flex-direction: column;- gap: 14px;- min-width: 0;+ gap: 16px;}-.field-grid {- display: grid;- grid-template-columns: 130px minmax(0, 1fr);- gap: 10px 12px;- align-items: center;+.form-item {+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;- label {- color: var(--td-text-color-secondary);+ &__label {+ color: var(--td-text-color-primary);font-size: 13px;+ font-weight: 500;+ }++ &__control {+ display: flex;+ align-items: flex-start;+ gap: 10px;}- .field-hint.span-all {- grid-column: 1 / -1;+ &__hint {margin: 0;color: var(--td-text-color-placeholder);font-size: 12px;line-height: 1.5;}++ &--switch .form-item__control {+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+ }}-.example-box {- border: 1px solid var(--td-component-stroke);- border-radius: 6px;- background: var(--td-bg-color-page);- overflow: hidden;+.examples {+ width: 100%;}-.example-title {- padding: 10px 12px;- border-bottom: 1px solid var(--td-component-stroke);- color: var(--td-text-color-secondary);- font-size: 12px;+.snippet-tabs {+ margin-bottom: 8px;++ :deep(.t-tabs__nav) {+ min-height: 36px;+ }++ :deep(.t-tabs__nav-item) {+ font-size: 13px;+ height: 36px;+ line-height: 36px;+ color: var(--td-text-color-secondary);+ }++ :deep(.t-tabs__nav-item.t-is-active) {+ color: var(--td-text-color-primary);+ font-weight: 500;+ }++ :deep(.t-tabs__bar) {+ background: var(--td-brand-color);+ }}-pre {- margin: 0;- padding: 12px;- overflow: auto;- font-family: var(--app-font-family-mono);- font-size: 12px;- line-height: 1.6;+.code-panel {+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);+ overflow: hidden;++ &__toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 8px 10px;+ border-bottom: 1px solid var(--td-component-stroke);+ background: var(--td-bg-color-container);+ }++ &__label {+ font-size: 12px;+ font-weight: 500;+ color: var(--td-text-color-secondary);+ }++ &__copy {+ flex-shrink: 0;++ :deep(.t-button__text) {+ display: inline-flex;+ align-items: center;+ }++ :deep(.t-icon) {+ display: inline-flex;+ align-items: center;+ }+ }++ &__pre {+ margin: 0;+ padding: 10px 12px;+ overflow: auto;+ font-family: var(--app-font-family-mono);+ font-size: 12px;+ line-height: 1.5;+ color: var(--td-text-color-primary);+ background: transparent;+ }}.actions {display: flex;justify-content: flex-end;+ margin-top: 4px;+ padding-top: 16px;+ border-top: 1px solid var(--td-component-stroke);}.mono-input :deep(input) {@@ -378,13 +559,51 @@ pre {}@media (max-width: 780px) {- .row,- .row--stack {+ .row {grid-template-columns: 1fr;}- .field-grid {- grid-template-columns: 1fr;+ .mode-radio {+ width: 100%;++ :deep(.t-radio-group) {+ display: flex;+ width: 100%;+ }++ :deep(.t-radio-button) {+ flex: 1 1 0;+ min-width: 0;+ }+ }++ .mode-detail {+ max-width: none;+ }+}++.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;+}</style>diff --git a/frontend/src/views/integrations/IntegrationsModal.vue b/frontend/src/views/integrations/IntegrationsModal.vueindex fc4e3ad5d..5c2d55df8 100644--- a/frontend/src/views/integrations/IntegrationsModal.vue+++ b/frontend/src/views/integrations/IntegrationsModal.vue@@ -57,7 +57,13 @@<AgentEmbedChannelPanel v-model:filter-agent-id="filterAgentId" /></div>- <ApiIntegrationSettings v-if="currentSection === 'api'" />+ <div v-if="currentSection === 'api'" class="section">+ <div class="section-header">+ <h2>{{ $t('integrations.api.title') }}</h2>+ <p class="section-description">{{ $t('integrations.api.subtitle') }}</p>+ </div>+ <ApiIntegrationSettings />+ </div><ChromeExtensionLanding v-if="currentSection === 'chrome'" /><ClawSkillLanding v-if="currentSection === 'claw'" /></div>@@ -212,7 +218,6 @@ watch(padding: 24px 28px 28px;&--landing {- padding-top: 44px;padding-right: 52px;padding-bottom: 20px;}