feat(embed): add widget, visitor chat, and management UI (#1657)

Add embed.html entrypoint, floating widget SDK, secure-mode snippets,
management panel with preview, visitor chat composables, citation rendering,
and integration docs for subdomain and server-side token exchange.
This commit is contained in:
wizardchen
2026-06-12 22:40:18 +08:00
committed by lyingbug
parent ed9802ff2b
commit 08852ab19d
41 changed files with 10186 additions and 745 deletions
+121
View File
@@ -0,0 +1,121 @@
/** Shared citation tag preprocessing for chat markdown (QA + agent). */
const ATTRIBUTE_REGEX = /([\w-]+)\s*=\s*"([^"]*)"/g
function parseTagAttributes(attrString: string): Record<string, string> {
const attributes: Record<string, string> = {}
if (!attrString) return attributes
ATTRIBUTE_REGEX.lastIndex = 0
let match: RegExpExecArray | null
while ((match = ATTRIBUTE_REGEX.exec(attrString)) !== null) {
attributes[match[1]] = match[2]
}
return attributes
}
function escapeHtml(text: string): string {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
function truncateMiddle(text: string, maxLength = 13): string {
if (!text) return ''
if (text.length <= maxLength) return text
const half = Math.floor((maxLength - 3) / 2)
const start = text.slice(0, half + ((maxLength - 3) % 2))
const end = text.slice(-half)
return `${start}...${end}`
}
/** Convert <web/> / <kb/> / [[wiki]] tags into inline citation HTML. */
export function preprocessCitationTags(contentStr: string): string {
if (!contentStr.trim()) return ''
return contentStr
.replace(/<web\b([^>]*)\/>/g, (_m, attrString: string) => {
const attrs = parseTagAttributes(attrString)
const url = attrs.url || ''
const title = attrs.title || ''
if (!url) return ''
let domain = url
try {
const u = new URL(url)
const host = u.hostname || ''
const parts = host.split('.')
domain = parts.length >= 2 ? parts.slice(-2).join('.') : host || url
} catch {
// keep original
}
const safeTitle = escapeHtml(title)
const safeUrl = escapeHtml(url)
return `<a class="citation citation-web" data-url="${safeUrl}" href="${safeUrl}" target="_blank" rel="noopener noreferrer"><span class="citation-icon web"></span><span class="citation-domain">${domain}</span><span class="citation-tip"><span class="tip-title">${safeTitle}</span><span class="tip-url">${safeUrl}</span></span></a>`
})
.replace(/<kb\b([^>]*)\/>/g, (_m, attrString: string) => {
const attrs = parseTagAttributes(attrString)
const doc = attrs.doc || ''
const chunkId = attrs.chunk_id || attrs.chunkId || ''
const kbId = attrs.kb_id || attrs.kbId || ''
if (!doc || !chunkId) return ''
const safeDoc = escapeHtml(doc)
const safeKbId = escapeHtml(kbId)
const safeChunkId = escapeHtml(chunkId)
const displayDoc = escapeHtml(truncateMiddle(doc))
return `<span class="citation citation-kb" data-kb-id="${safeKbId}" data-chunk-id="${safeChunkId}" data-doc="${safeDoc}" role="button" tabindex="0"><span class="citation-icon kb"></span><span class="citation-text">${displayDoc}</span><span class="citation-tip"><span class="tip-loading">…</span></span></span>`
})
.replace(/\[\[([^\]]+)\]\]/g, (match, inner: string) => {
const pipeIdx = inner.indexOf('|')
const slug = pipeIdx > 0 ? inner.substring(0, pipeIdx).trim() : inner.trim()
if (!slug) return match
let display = slug
if (pipeIdx > 0) {
display = inner.substring(pipeIdx + 1).trim()
} else {
const parts = slug.split('/')
display = parts.length > 1 ? parts.slice(1).join('/') : slug
}
return `<a href="#" class="wiki-content-link citation-wiki" data-slug="${escapeHtml(slug)}">${escapeHtml(display)}</a>`
})
}
const HTML_PLACEHOLDER_RE = /@@WEKNORA_HTML_PLACEHOLDER_(\d+)@@/g
/** Protect citation HTML from markdown parser; restore after marked.parse. */
export function extractCitationHtmlPlaceholders(contentStr: string): { content: string; htmlSnippets: string[] } {
const htmlSnippets: string[] = []
const storeHtml = (html: string): string => {
const idx = htmlSnippets.length
htmlSnippets.push(html)
return `@@WEKNORA_HTML_PLACEHOLDER_${idx}@@`
}
const content = contentStr
.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => storeHtml(preprocessCitationTags(match)))
.replace(/\[\[([^\]]+)\]\]/g, (match) => storeHtml(preprocessCitationTags(match)))
return { content, htmlSnippets }
}
export function restoreCitationHtmlPlaceholders(html: string, htmlSnippets: string[]): string {
if (!htmlSnippets.length) return html
return html.replace(HTML_PLACEHOLDER_RE, (_match, idx) => htmlSnippets[Number(idx)] || '')
}
/** Preserve raw <kb>/<web> tags before sanitizers that would strip them. */
export function preserveCitationTags(contentStr: string): { text: string; tags: string[] } {
const tags: string[] = []
const text = contentStr.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => {
const idx = tags.length
tags.push(match)
return `\x00TAG${idx}\x00`
})
return { text, tags }
}
export function restoreCitationTags(text: string, tags: string[]): string {
return text.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tags[Number(idx)] || '')
}
+43
View File
@@ -0,0 +1,43 @@
export type AllowedOriginsValidationError =
| { code: 'required' }
| { code: 'wildcard_prod' }
| { code: 'invalid'; origin: string }
/** Mirrors backend validateAllowedOrigins in internal/handler/embed_channel.go */
export function parseAllowedOrigins(text: string): string[] {
return text
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
}
export function validateAllowedOrigins(
origins: string[],
prod = import.meta.env.PROD,
): { ok: true; origins: string[] } | { ok: false; error: AllowedOriginsValidationError } {
const cleaned = parseAllowedOrigins(origins.join('\n'))
if (cleaned.length === 0) {
return { ok: false, error: { code: 'required' } }
}
for (const origin of cleaned) {
if (origin === '*') {
if (prod) {
return { ok: false, error: { code: 'wildcard_prod' } }
}
continue
}
let host = origin
if (origin.startsWith('*.')) {
host = `https://${origin.slice(2)}`
}
try {
const url = new URL(host)
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.host) {
return { ok: false, error: { code: 'invalid', origin } }
}
} catch {
return { ok: false, error: { code: 'invalid', origin } }
}
}
return { ok: true, origins: cleaned }
}
+24
View File
@@ -0,0 +1,24 @@
/** Resolve the public origin used in embed iframe / widget URLs. */
export function resolveEmbedBaseUrl(): string {
if (typeof window === 'undefined') return ''
const runtime = (window as Window & { __RUNTIME_CONFIG__?: { EMBED_BASE_URL?: string } }).__RUNTIME_CONFIG__
const fromRuntime = runtime?.EMBED_BASE_URL?.trim()
if (fromRuntime) {
try {
const u = new URL(fromRuntime, window.location.href)
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
} catch {
// fall through
}
}
const fromEnv = import.meta.env.VITE_EMBED_BASE_URL?.trim()
if (fromEnv) {
try {
const u = new URL(fromEnv, window.location.href)
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
} catch {
// fall through
}
}
return window.location.origin
}
+12
View File
@@ -0,0 +1,12 @@
/** Prefix host-injected context onto the user query for embed chat. */
export function buildQueryWithHostContext(
query: string,
hostContext?: Record<string, unknown>,
): string {
if (!hostContext || !Object.keys(hostContext).length) return query
const lines = Object.entries(hostContext)
.filter(([, v]) => v !== undefined && v !== null && v !== '')
.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`)
if (!lines.length) return query
return `[Host context]\n${lines.join('\n')}\n\n${query}`
}
+14
View File
@@ -0,0 +1,14 @@
export function isEmbedImageFile(file: File): boolean {
if (file.type.startsWith('image/')) return true
const name = file.name.toLowerCase()
return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'].some((ext) => name.endsWith(ext))
}
export function fileToDataURI(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result || ''))
reader.onerror = reject
reader.readAsDataURL(file)
})
}
+25
View File
@@ -0,0 +1,25 @@
/** Lightweight toast for embed bundle (no TDesign). */
export function embedToast(message: string, type: 'error' | 'info' = 'error') {
if (!message || typeof document === 'undefined') return
const el = document.createElement('div')
el.textContent = message
el.setAttribute('role', 'alert')
Object.assign(el.style, {
position: 'fixed',
left: '50%',
top: '16px',
transform: 'translateX(-50%)',
zIndex: '2147483647',
maxWidth: 'min(90vw, 420px)',
padding: '10px 14px',
borderRadius: '8px',
fontSize: '14px',
lineHeight: '1.4',
boxShadow: '0 4px 16px rgba(0,0,0,.12)',
background: type === 'error' ? '#fff1f0' : '#f6ffed',
color: type === 'error' ? '#cf1322' : '#389e0d',
border: `1px solid ${type === 'error' ? '#ffccc7' : '#b7eb8f'}`,
})
document.body.appendChild(el)
window.setTimeout(() => el.remove(), 4000)
}
+87 -50
View File
@@ -1,12 +1,11 @@
import mermaid from 'mermaid';
import type {Tokens} from 'marked';
import {openMermaidFullscreen} from "@/utils/mermaidViewer.ts";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import type { Tokens } from 'marked'
import { openMermaidFullscreen } from '@/utils/mermaidViewer.ts'
hljs.registerAliases("mermaid", { languageName: "plaintext" });
let mermaidInitialized = false;
let mermaidMod: typeof import('mermaid') | null = null
let hljsMod: typeof import('highlight.js') | null = null
let mermaidInitialized = false
let initPromise: Promise<void> | null = null
let hljsPromise: Promise<typeof import('highlight.js').default> | null = null
const MERMAID_CONFIG = {
startOnLoad: false,
@@ -34,63 +33,101 @@ const MERMAID_CONFIG = {
barGap: 4,
topPadding: 50,
},
};
}
async function getMermaid() {
if (!mermaidMod) {
mermaidMod = await import('mermaid')
}
return mermaidMod.default
}
async function getHljs() {
if (!hljsMod) {
hljsMod = await import('highlight.js')
await import('highlight.js/styles/github.css')
hljsMod.default.registerAliases('mermaid', { languageName: 'plaintext' })
}
return hljsMod.default
}
function escapeHtml(text: string) {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
export const ensureMermaidInitialized = () => {
if (mermaidInitialized) return;
mermaid.initialize(MERMAID_CONFIG as any);
mermaidInitialized = true;
};
if (!initPromise) {
initPromise = (async () => {
const mermaid = await getMermaid()
if (!mermaidInitialized) {
mermaid.initialize(MERMAID_CONFIG as Parameters<typeof mermaid.initialize>[0])
mermaidInitialized = true
}
})()
}
}
let mermaidCount = 0;
let mermaidCount = 0
export const createMermaidCodeRenderer = (idPrefix: string) => {
return ({text, lang}: Tokens.Code) => {
let highlighted = '';
let highlightLang: string = lang || 'Code';
if (highlightLang && hljs.getLanguage(highlightLang)) {
if (!hljsPromise) {
hljsPromise = getHljs()
}
return ({ text, lang }: Tokens.Code) => {
let highlighted = escapeHtml(text)
let highlightLang: string = lang || 'Code'
const hljs = hljsMod?.default
if (hljs) {
if (highlightLang && hljs.getLanguage(highlightLang)) {
try {
highlighted = hljs.highlight(text, { language: lang }).value;
highlighted = hljs.highlight(text, { language: highlightLang }).value
} catch {
let ret = hljs.highlightAuto(text);
highlighted = ret.value;
highlightLang = ret.language || "Code";
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
} else {
let ret = hljs.highlightAuto(text);
highlighted = ret.value;
highlightLang = ret.language || "Code";
} else {
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
}
if (lang === 'mermaid') {
const id = `${idPrefix}-${++mermaidCount}`;
return `<pre id="${id}" data-mermaid="false"><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`;
const id = `${idPrefix}-${++mermaidCount}`
return `<pre id="${id}" data-mermaid="false"><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`
}
return `<pre><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`;
};
};
return `<pre><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`
}
}
export const renderMermaidInContainer = async (
rootElement: HTMLElement | null | undefined,
) => {
if (!rootElement) return 0;
const mermaidElements = rootElement.querySelectorAll<HTMLElement>('pre[data-mermaid="false"]');
if (!rootElement) return
const mermaid = await getMermaid()
ensureMermaidInitialized()
await initPromise
const mermaidElements = rootElement.querySelectorAll<HTMLElement>('pre[data-mermaid="false"]')
for (const el of mermaidElements) {
try{
const code = el.innerText;
// 验证
await mermaid.parse(code);
// 渲染
let {svg} = await mermaid.render(`${el.id}-svg`, code);
el.classList.add('mermaid')
el.innerHTML = svg;
el.onclick = (event) => {
event.stopPropagation();
openMermaidFullscreen(svg);
};
} catch(e){
console.error("Mermaid rendering error:", e);
try {
const code = el.innerText
await mermaid.parse(code)
const { svg } = await mermaid.render(`${el.id}-svg`, code)
el.classList.add('mermaid')
el.innerHTML = svg
el.onclick = (event) => {
event.stopPropagation()
openMermaidFullscreen(svg)
}
} catch (e) {
console.error('Mermaid rendering error:', e)
}
// 标记为已渲染
el.setAttribute('data-mermaid', 'true');
el.setAttribute('data-mermaid', 'true')
}
};
}
+37 -10
View File
@@ -28,10 +28,16 @@ function getCurrentLanguage(): string {
instance.interceptors.request.use(
(config) => {
// 添加JWT token认证
const token = localStorage.getItem('weknora_token');
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
const existingAuth = config.headers?.Authorization ?? config.headers?.authorization;
const isEmbedAuth = typeof existingAuth === 'string' && existingAuth.startsWith('Embed ');
const isEmbedPath = typeof config.url === 'string' && config.url.includes('/api/v1/embed/');
// 嵌入渠道使用 Embed token;勿用本地 JWT 覆盖(否则调试页会 401)
if (!isEmbedAuth) {
const token = localStorage.getItem('weknora_token');
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
}
// 添加用户语言偏好
@@ -46,9 +52,11 @@ instance.interceptors.request.use(
// 换之后只有第一批请求带 X-Tenant-ID"调成永久状态。
// 后端 IsTenantAccessible 已经允许 header 指向 home 租户(自家),
// 所以无脑附不会引入新风险。
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
if (selectedTenantId) {
config.headers["X-Tenant-ID"] = selectedTenantId;
if (!isEmbedAuth && !isEmbedPath) {
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
if (selectedTenantId) {
config.headers["X-Tenant-ID"] = selectedTenantId;
}
}
config.headers["X-Request-ID"] = `${generateRandomString(12)}`;
@@ -68,7 +76,7 @@ let failedQueue: Array<{ resolve: Function; reject: Function }> = [];
// must surface to the page (e.g. expired token), not trigger the
// refresh-then-redirect-to-login flow (issue #1617). '/auth/register' already
// covers '/auth/register-by-invite' via substring match.
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup'];
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup', '/api/v1/embed/'];
function isPublicAuthRequest(url?: string): boolean {
if (!url) return false;
@@ -88,9 +96,16 @@ const processQueue = (error: any, token: string | null = null) => {
failedQueue = [];
};
function isEmbedPage(): boolean {
if (typeof window === 'undefined') return false;
return window.location.pathname.startsWith('/embed/');
}
function redirectToLogin() {
if (typeof window === 'undefined') return;
if (window.location.pathname === '/login') return;
// Embed 渠道用 Embed token 鉴权,匿名访问不应被踢到登录页
if (isEmbedPage()) return;
window.location.href = '/login';
}
@@ -112,9 +127,21 @@ instance.interceptors.response.use(
}
// 公开接口(auto-setup / login / register / oidc)的 401 不走 refresh 逻辑,直接返回错误
if (error.response.status === 401 && isPublicAuthRequest(originalRequest?.url)) {
if ((error.response.status === 401 || error.response.status === 403) && isPublicAuthRequest(originalRequest?.url)) {
const { status, data } = error.response;
return Promise.reject({ status, message: (typeof data === 'object' ? (data?.error?.message || data?.message) : data) || t('error.invalidCredentials') });
const msg = typeof data === 'object'
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
: data;
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
}
// Embed 调试页/挂件:无 JWT 时直接拒绝,勿走 refresh → /login
if (error.response.status === 401 && isEmbedPage()) {
const { status, data } = error.response;
const msg = typeof data === 'object'
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
: data;
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
}
// 如果是401错误且不是刷新token的请求,尝试刷新token
+18 -4
View File
@@ -312,7 +312,10 @@ export function clearProtectedFileFailureCache(): void {
protectedFileFailureCache.clear();
}
export async function hydrateProtectedFileImages(root: ParentNode | null | undefined): Promise<void> {
export async function hydrateProtectedFileImages(
root: ParentNode | null | undefined,
embed?: { channelId: string; token: string },
): Promise<void> {
if (!root || typeof window === 'undefined') {
return;
}
@@ -324,7 +327,11 @@ export async function hydrateProtectedFileImages(root: ParentNode | null | undef
return;
}
const headers = getProtectedFileRequestHeaders();
// Embed visitors carry no Bearer/tenant context; route through the
// embed-scoped file proxy (auth via the Embed header, tenant from the channel).
const headers = embed
? { Authorization: `Embed ${embed.token}` }
: getProtectedFileRequestHeaders();
await Promise.all(Array.from(images).map(async (img) => {
const protectedSrc = (img.getAttribute('data-protected-src') || '').trim();
@@ -339,11 +346,18 @@ export async function hydrateProtectedFileImages(root: ParentNode | null | undef
img.dataset.authHydrated = '1';
const isProviderScheme = /^(local|minio|cos|tos|s3|oss|ks3|obs):\/\//.test(sourceURL);
const fileProxyBase = embed
? `/api/v1/embed/${embed.channelId}/files`
: '/files';
const requestURL = isProviderScheme
? `/files?${new URLSearchParams({ file_path: sourceURL }).toString()}`
? `${fileProxyBase}?${new URLSearchParams({ file_path: sourceURL }).toString()}`
: sourceURL;
if (!requestURL.startsWith('/files?') || !requestURL.includes('file_path=')) {
const isProxyRequest =
requestURL.includes('file_path=') &&
(requestURL.startsWith('/files?') ||
/^\/api\/v1\/embed\/[^/]+\/files\?/.test(requestURL));
if (!isProxyRequest) {
img.dataset.authHydrated = '0';
return;
}