diff --git a/docs/embed-secure-mode.md b/docs/embed-secure-mode.md new file mode 100644 index 00000000..39cf4036 --- /dev/null +++ b/docs/embed-secure-mode.md @@ -0,0 +1,182 @@ +# Embed 安全模式 + +> **一句话**:长期密钥(发布 Token `em_…`)只放在**你自己的服务器**;访客浏览器里只有 30 分钟有效的短时令牌(`ems_…`)。 + +## 为什么要用? + +| 方式 | 发布 Token 在哪 | 风险 | +|------|-----------------|------| +| iframe / 普通 Widget | 写在页面 HTML 或 URL hash 里 | 任何人「查看源代码」就能复制,等于公开密钥 | +| **安全模式 Widget** | 仅环境变量 / 密钥管理,在服务端 | 浏览器拿不到长期密钥;还可先校验访客是否登录 | + +生产环境对外嵌入,**应优先用安全模式**。 + +## 两种 Token + +| 名称 | 格式 | 谁持有 | 用途 | +|------|------|--------|------| +| 发布 Token | `em_…` | 仅你的服务端 | 向 WeKnora 换取短时令牌;在管理端「渠道密钥」查看 | +| 会话 Token | `ems_…` | 访客浏览器(iframe 内) | 调聊天、上传等 embed API;约 30 分钟过期,Widget 会自动刷新 | + +## 工作流程 + +``` +访客浏览器 你的后端(shop 的服务器) WeKnora + │ │ │ + │ 1. 加载 Widget │ │ + │ data-token-endpoint │ │ + │ (不含 em_) │ │ + │─────────────────────────────►│ │ + │ │ 2. 校验访客已登录(可选) │ + │ │ 3. POST .../embed/:id/exchange │ + │ │ Authorization: Embed em_… │ + │ │─────────────────────────────►│ + │ │◄──── session_token (ems_…) ───│ + │◄── 4. { token, expiresIn } ──│ │ + │ 5. iframe 用 ems_ 聊天 │ │ +``` + +对应管理端「嵌入渠道 → 安全模式」里的两段代码: + +1. **页面脚本**:`data-token-endpoint="https://你的域名/weknora/embed-token"`(没有 `data-token`) +2. **服务端接口**:用发布 Token 调 exchange,把 `ems_…` 返回给前端 + +## 集成步骤 + +### 第 1 步:在 WeKnora 创建渠道 + +- 记下 **渠道 ID** 和 **发布 Token**(`em_…`) +- 配置域名白名单(见下) +- 配置分钟 / 日限流 + +### 第 2 步:部署取令牌接口 + +在你的业务后端新增一个 HTTP 接口(路径自定),要求: + +**入参**:浏览器 GET 请求(Widget 会 `fetch` 这个地址) + +**你必须做**: + +- 校验调用方是合法访客(Session Cookie、JWT 等),未登录返回 `401` +- 用发布 Token 调 WeKnora exchange +- 成功时返回 JSON:`{ "token": "", "expiresIn": 1800 }` + +**调 exchange 的约定**: + +```http +POST https:///api/v1/embed//exchange +Authorization: Embed <发布 Token em_…> +Origin: https://<你的业务站点> ← 须与渠道白名单一致,否则 403 +``` + +> 服务端 `fetch` 默认不带 `Origin`,需要**手动设置**与白名单匹配的 `Origin` 头。 + +### 第 3 步:粘贴安全模式 Widget 代码 + +把 `data-token-endpoint` 改成上一步的真实 URL。完整示例在管理端「安全模式」Tab 可复制。 + +## 服务端示例 + +以下 ``、`` 替换为实际值;发布 Token 放环境变量 `WEKNORA_PUBLISH_TOKEN`,**不要**写进前端。 + +### Node.js(Express) + +```javascript +const WEKNORA_BASE = 'https://'; +const CHANNEL_ID = ''; +const ALLOWED_ORIGIN = 'https://shop.example.com'; // 与渠道白名单一致 + +app.get('/weknora/embed-token', async (req, res) => { + const hasSession = Boolean(req.cookies?.session_id); + const auth = req.headers.authorization || ''; + if (!hasSession && !auth.startsWith('Bearer ')) { + return res.status(401).json({ error: 'unauthorized' }); + } + + const r = await fetch(`${WEKNORA_BASE}/api/v1/embed/${CHANNEL_ID}/exchange`, { + method: 'POST', + headers: { + Authorization: 'Embed ' + process.env.WEKNORA_PUBLISH_TOKEN, + Origin: ALLOWED_ORIGIN, + }, + }); + const body = await r.json(); + if (!body?.data?.session_token) { + return res.status(502).json({ error: 'mint failed' }); + } + res.json({ token: body.data.session_token, expiresIn: body.data.expires_in }); +}); +``` + +### Go(net/http) + +```go +func embedTokenHandler(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "" && r.Header.Get("Cookie") == "" { + http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) + return + } + req, _ := http.NewRequest(http.MethodPost, + "https:///api/v1/embed//exchange", nil) + req.Header.Set("Authorization", "Embed "+os.Getenv("WEKNORA_PUBLISH_TOKEN")) + req.Header.Set("Origin", "https://shop.example.com") // 与渠道白名单一致 + resp, err := http.DefaultClient.Do(req) + if err != nil || resp.StatusCode >= 300 { + http.Error(w, `{"error":"mint failed"}`, http.StatusBadGateway) + return + } + defer resp.Body.Close() + var body struct { + Data struct { + SessionToken string `json:"session_token"` + ExpiresIn int `json:"expires_in"` + } `json:"data"` + } + if json.NewDecoder(resp.Body).Decode(&body) != nil || body.Data.SessionToken == "" { + http.Error(w, `{"error":"mint failed"}`, http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{ + "token": body.Data.SessionToken, "expiresIn": body.Data.ExpiresIn, + }) +} +``` + +管理端「安全模式 → 服务端示例」Tab 会按当前渠道 ID 生成带真实 URL 的片段。 + +## 域名白名单怎么填? + +| 要放行的请求来源 | 白名单示例 | +|------------------|------------| +| 聊天 iframe 所在源站(embed 页面) | `https://app.example.com` 或 `https://embed.example.com` | +| 你的取令牌后端(exchange 时带的 Origin) | `https://shop.example.com` | + +若 embed 使用[独立子域](./embed-subdomain.md),**两条都要加**(embed 源站 + 业务后端源站)。 + +开发环境可临时使用 `*`;**生产环境禁止 `*`**。 + +## 上线检查 + +- [ ] 发布 Token 仅通过环境变量 / 密钥服务注入,未提交到 Git、未打进前端静态包 +- [ ] 取令牌接口校验访客身份 +- [ ] 全链路 HTTPS +- [ ] 白名单已包含 embed 源站与 exchange 使用的 Origin +- [ ] 已配置限流;敏感智能体不要用普通模式把 Token 暴露在网页里 +- [ ] 轮换发布 Token 后,同步更新服务端环境变量 + +## 常见问题 + +| 现象 | 原因与处理 | +|------|------------| +| exchange 返回 **401** / `publish token required` | 发布 Token 错误、已轮换,或误用了 `ems_` 会话 Token | +| exchange 或聊天 API 返回 **403** `origin not allowed` | 白名单未包含当前请求的 `Origin`;服务端 exchange 记得手动加 `Origin` 头 | +| iframe 一直「等待 Token」 | `token-endpoint` 未返回 `{ token, expiresIn }`,或 CORS 未允许 Widget 所在源站访问你的接口 | +| 取令牌接口 **502** `mint failed` | WeKnora 不可达、渠道已停用,或 exchange 响应格式不对 | +| 访客随便就能聊 | 取令牌接口未做登录校验——在 exchange 前加 Session / JWT 检查 | + +## 相关 + +- 可选:embed 独立子域 → [embed-subdomain.md](./embed-subdomain.md) +- Widget SDK 注释:`frontend/public/weknora-widget.js` +- 代码生成:`frontend/src/api/embed/index.ts` diff --git a/docs/embed-subdomain.md b/docs/embed-subdomain.md new file mode 100644 index 00000000..863b7974 --- /dev/null +++ b/docs/embed-subdomain.md @@ -0,0 +1,106 @@ +# Embed 独立子域部署(可选) + +> **一句话**:把聊天页面单独放到 `embed.example.com`,与主站 `app.example.com` 分开。**大多数部署不需要这一步**——主站和 embed 同域就能用。只有对安全隔离有明确要求时再考虑。 + +## 先搞清楚三个「网站」 + +嵌入聊天时,实际涉及三类地址(可以相同,也可以不同): + +| 角色 | 举例 | 干什么 | +|------|------|--------| +| **A. 业务站点(宿主)** | `https://shop.example.com` | 你的商城 / 文档站;在这里粘贴 Widget 脚本或 iframe | +| **B. Embed 页面源站** | `https://app.example.com` 或 `https://embed.example.com` | 提供 `embed.html`、`weknora-widget.js`;聊天 iframe 加载自这里 | +| **C. WeKnora API** | 通常与 B 同域,如 `https://app.example.com/api` | 后端接口 | + +**默认(推荐入门)**:B 和主站管理后台都在 `https://app.example.com`,A 可以是任意第三方域名。 + +``` +shop.example.com app.example.com +┌─────────────────┐ ┌──────────────────────────┐ +│ + + +
+ + + diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 994c2a5f..53c7d0a3 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -1,3 +1,17 @@ +# Optional dedicated embed origin — uncomment and set server_name (e.g. embed.example.com). +# Serve only embed.html + static assets; proxy /api to the WeKnora backend. +# See docs/embed-subdomain.md +# +# server { +# listen 80; +# server_name embed.example.com; +# client_max_body_size ${MAX_FILE_SIZE}; +# location = /weknora-widget.js { root /usr/share/nginx/html; } +# location ^~ /embed/ { root /usr/share/nginx/html; try_files $uri $uri/ /embed.html; } +# location ^~ /assets/ { root /usr/share/nginx/html; add_header Cache-Control "public, max-age=31536000, immutable"; } +# location /api/ { proxy_pass http://weknora-backend:8080; proxy_set_header Host $host; } +# } + server { listen 80; server_name localhost; @@ -24,6 +38,23 @@ server { error_log /var/log/nginx/error.log warn; access_log /var/log/nginx/access.log; + # Static widget loader for third-party sites + location = /weknora-widget.js { + root /usr/share/nginx/html; + add_header Cache-Control "public, max-age=3600" always; + add_header X-Content-Type-Options "nosniff" always; + } + + # Embed widget pages may be loaded inside third-party iframes (lightweight embed.html) + location ^~ /embed/ { + root /usr/share/nginx/html; + try_files $uri $uri/ /embed.html; + add_header Cache-Control "no-cache, must-revalidate" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + } + # 前端静态文件 location / { root /usr/share/nginx/html; diff --git a/frontend/public/config.js b/frontend/public/config.js index 2861e241..9b4da289 100644 --- a/frontend/public/config.js +++ b/frontend/public/config.js @@ -1,4 +1,6 @@ // 运行时配置(本地开发默认值,Docker 环境会被 entrypoint 脚本覆盖) window.__RUNTIME_CONFIG__ = { - MAX_FILE_SIZE_MB: 50 + MAX_FILE_SIZE_MB: 50, + // Optional: serve embed on a dedicated origin, e.g. 'https://embed.example.com' + EMBED_BASE_URL: '', }; diff --git a/frontend/public/weknora-widget.js b/frontend/public/weknora-widget.js new file mode 100644 index 00000000..3207d011 --- /dev/null +++ b/frontend/public/weknora-widget.js @@ -0,0 +1,434 @@ +/** + * WeKnora embed widget SDK — floating chat launcher. + * + * Programmatic: + * WeKnora.init({ channel, token, position, primaryColor, title, baseUrl }) + * WeKnora.open() | close() | toggle() | destroy() + * WeKnora.on('ready', fn) | off('ready', fn) + * + * Host context & actions (postMessage to iframe): + * WeKnora.setContext({ userId, page, ... }) + * Inject visitor/page context merged into each chat query. + * WeKnora.openWithQuery('How do I reset my password?') + * Opens the panel (if closed) and sends the query when the iframe is ready. + * WeKnora.setLocale('en-US') + * Switch embed UI language (zh-CN | en-US | ko-KR | ru-RU). + * + * Secure mode (recommended): instead of `token`, pass `tokenEndpoint` — a URL on + * your own backend that returns { token: "ems_...", expiresIn: 1800 }. Your + * backend mints that short-lived session token by exchanging the publish token + * (kept server-side) against POST /api/v1/embed/:channel/exchange. The publish + * token then never reaches the browser; the widget auto-refreshes before expiry. + * + * Legacy script-tag auto-init via data-* attributes on the script element + * (data-channel + data-token, or data-channel + data-token-endpoint). + */ +(function (global) { + 'use strict'; + + var HOST_SOURCE = 'weknora-host'; + var EMBED_SOURCE = 'weknora-embed'; + var POSITIONS = ['bottom-right', 'bottom-left', 'top-right', 'top-left']; + var DEFAULT_POSITION = 'bottom-right'; + var DEFAULT_COLOR = '#07C05F'; + var DEFAULT_TITLE = 'AI Assistant'; + var DEFAULT_WIDTH = 400; + var DEFAULT_HEIGHT = 600; + + var instance = null; + var listeners = {}; + + function normalizePosition(pos) { + if (!pos || POSITIONS.indexOf(pos) < 0) return DEFAULT_POSITION; + return pos; + } + + function positionStyles(position, kind) { + var isLeft = position.indexOf('left') >= 0; + var isTop = position.indexOf('top') >= 0; + var horizontal = isLeft ? 'left:24px' : 'right:24px'; + if (kind === 'launcher') { + return horizontal + ';' + (isTop ? 'top:24px' : 'bottom:24px'); + } + return horizontal + ';' + (isTop ? 'top:88px' : 'bottom:88px'); + } + + function emit(event, payload) { + var handlers = listeners[event]; + if (!handlers) return; + handlers.slice().forEach(function (fn) { + try { fn(payload); } catch (e) { console.error('[WeKnora]', e); } + }); + } + + function createWidget(opts) { + var channelId = opts.channel || opts.channelId; + // Insecure mode: a long-lived publish token is embedded in the page. + var staticToken = opts.token; + // Secure mode: the page never holds the publish token. Instead it points at + // an endpoint on the integrator's own backend that mints a short-lived + // session token (by server-side exchange of the publish token). The widget + // fetches a fresh token here and refreshes it before expiry. + var tokenEndpoint = opts.tokenEndpoint || opts.token_endpoint || ''; + if (!channelId || (!staticToken && !tokenEndpoint)) { + console.warn('[WeKnora] channel and (token or tokenEndpoint) are required'); + return null; + } + + var currentToken = staticToken || ''; + var tokenInFlight = null; + var refreshTimer = null; + + function scheduleRefresh(expiresInSec) { + if (!tokenEndpoint) return; + if (refreshTimer) clearTimeout(refreshTimer); + var ttl = Number(expiresInSec) > 0 ? Number(expiresInSec) : 1800; + // Refresh at ~80% of the lifetime, never sooner than 30s. + var delayMs = Math.max(Math.floor(ttl * 0.8), 30) * 1000; + refreshTimer = setTimeout(function () { + loadToken(true).then(function (tok) { + if (tok) provideToken(); + }).catch(function () { /* keep last token; next interaction retries */ }); + }, delayMs); + } + + // Returns a Promise resolving to a usable token. In static mode this is the + // embedded publish token. In secure mode it fetches from tokenEndpoint. + function loadToken(force) { + if (staticToken) return Promise.resolve(staticToken); + if (currentToken && !force) return Promise.resolve(currentToken); + if (tokenInFlight) return tokenInFlight; + tokenInFlight = fetch(tokenEndpoint, { + method: 'GET', + credentials: 'include', + headers: { Accept: 'application/json' }, + }) + .then(function (res) { + if (!res.ok) throw new Error('token endpoint HTTP ' + res.status); + return res.json(); + }) + .then(function (data) { + var d = data || {}; + var inner = d.data || d; + var tok = inner.token || inner.session_token || ''; + var expiresIn = inner.expiresIn || inner.expires_in || 0; + if (!tok) throw new Error('token endpoint returned no token'); + currentToken = tok; + scheduleRefresh(expiresIn); + return tok; + }) + .catch(function (e) { + console.error('[WeKnora] failed to load token', e); + throw e; + }) + .then(function (tok) { tokenInFlight = null; return tok; }, function (e) { tokenInFlight = null; throw e; }); + return tokenInFlight; + } + + var position = normalizePosition(opts.position); + var primaryColor = opts.primaryColor || opts.primary_color || DEFAULT_COLOR; + var title = opts.title || DEFAULT_TITLE; + var baseUrl = (opts.baseUrl || opts.base || '').replace(/\/$/, ''); + if (!baseUrl) { + var script = document.currentScript; + if (script && script.src) { + baseUrl = script.src.replace(/\/weknora-widget\.js.*$/, ''); + } else { + baseUrl = global.location ? global.location.origin : ''; + } + } + + var panelWidth = Number(opts.width) > 0 ? Number(opts.width) : DEFAULT_WIDTH; + var panelHeight = Number(opts.height) > 0 ? Number(opts.height) : DEFAULT_HEIGHT; + var embedUrl = baseUrl + '/embed/' + encodeURIComponent(channelId); + var embedOrigin = baseUrl; + try { + // Derive the exact origin (scheme + host + port) rather than trusting the + // raw baseUrl string, so postMessage origin checks are precise. + embedOrigin = new URL(embedUrl, global.location ? global.location.href : undefined).origin; + } catch (e) { + embedOrigin = baseUrl; + } + var destroyed = false; + var panelOpen = false; + var iframeReady = false; + var iframeOrigin = ''; + + var launcher = document.createElement('button'); + launcher.type = 'button'; + launcher.setAttribute('aria-label', title); + launcher.textContent = '💬'; + launcher.style.cssText = [ + 'position:fixed', + 'z-index:2147483000', + 'width:56px', + 'height:56px', + 'border-radius:50%', + 'border:none', + 'cursor:pointer', + 'font-size:24px', + 'box-shadow:0 4px 16px rgba(0,0,0,.18)', + 'background:' + primaryColor, + 'color:#fff', + 'opacity:0.92', + 'transition:opacity .2s', + positionStyles(position, 'launcher'), + ].join(';'); + + var panel = document.createElement('div'); + panel.style.cssText = [ + 'position:fixed', + 'z-index:2147482999', + 'width:' + panelWidth + 'px', + 'max-width:calc(100vw - 32px)', + 'height:' + panelHeight + 'px', + 'max-height:calc(100vh - 100px)', + 'border-radius:12px', + 'overflow:hidden', + 'box-shadow:0 8px 32px rgba(0,0,0,.2)', + 'display:none', + 'background:#fff', + positionStyles(position, 'panel'), + ].join(';'); + + var iframe = document.createElement('iframe'); + iframe.src = embedUrl; + iframe.style.cssText = 'width:100%;height:100%;border:none'; + iframe.setAttribute('allow', 'clipboard-write'); + var hostOrigin = ''; + try { + hostOrigin = global.location ? global.location.origin : ''; + } catch (e) { hostOrigin = ''; } + var crossOriginEmbed = hostOrigin && embedOrigin && hostOrigin !== embedOrigin; + var sandboxAttr = String(opts.sandbox || opts.sandboxMode || '').trim(); + if (!sandboxAttr && opts.scriptEl) { + sandboxAttr = String(opts.scriptEl.getAttribute('data-sandbox') || '').trim(); + } + if (sandboxAttr === 'true' || sandboxAttr === '1') { + sandboxAttr = 'allow-scripts allow-forms allow-popups allow-modals allow-same-origin'; + } + if (!sandboxAttr && crossOriginEmbed) { + sandboxAttr = 'allow-scripts allow-forms allow-popups allow-modals allow-same-origin'; + } + if (sandboxAttr && sandboxAttr !== 'false' && sandboxAttr !== '0') { + iframe.setAttribute('sandbox', sandboxAttr); + } + iframe.setAttribute('title', title); + panel.appendChild(iframe); + + function isTrustedOrigin(origin) { + if (!origin || origin === 'null') return false; + return origin === embedOrigin; + } + + function postToIframe(message) { + if (!iframe.contentWindow) return; + // Always target the known embed origin; never fall back to '*' so the + // publish token can't leak to an unexpected document. + iframe.contentWindow.postMessage(message, embedOrigin || '/'); + } + + function provideToken() { + loadToken(false).then(function (tok) { + if (!tok) return; + postToIframe({ + source: HOST_SOURCE, + type: 'provide_token', + token: tok, + channel_id: channelId, + }); + }).catch(function () { /* already logged; iframe stays awaiting */ }); + } + + function postHostPayload(type, payload) { + if (!iframe.contentWindow) { + console.warn('[WeKnora] iframe not ready'); + return false; + } + postToIframe({ source: HOST_SOURCE, type: type, payload: payload || {} }); + return true; + } + + function whenIframeReady(fn, attempt) { + var tries = attempt || 0; + if (iframeReady && iframe.contentWindow) { + fn(); + return; + } + if (tries >= 20) { + console.warn('[WeKnora] iframe not ready'); + return; + } + setTimeout(function () { whenIframeReady(fn, tries + 1); }, 100); + } + + function setContext(ctx) { + if (!ctx || typeof ctx !== 'object') { + console.warn('[WeKnora] setContext expects an object'); + return; + } + postHostPayload('set_context', ctx); + } + + function openWithQuery(query) { + var text = String(query || '').trim(); + if (!text) { + console.warn('[WeKnora] openWithQuery requires a non-empty query'); + return; + } + setOpen(true); + whenIframeReady(function () { + postHostPayload('open_with_query', { query: text }); + }); + } + + function setLocale(locale) { + var loc = String(locale || '').trim(); + if (!loc) { + console.warn('[WeKnora] setLocale requires a locale string'); + return; + } + postHostPayload('set_locale', { locale: loc }); + } + + function onMessage(e) { + // Only trust messages coming from our own iframe window and origin. + if (e.source !== iframe.contentWindow) return; + if (!isTrustedOrigin(e.origin)) return; + if (!e.data || e.data.source !== EMBED_SOURCE) return; + if (e.data.channel_id && e.data.channel_id !== channelId) return; + + if (!iframeOrigin) { + iframeOrigin = e.origin; + } + + switch (e.data.type) { + case 'bootstrap_request': + provideToken(); + break; + case 'ready': + iframeReady = true; + launcher.style.opacity = '1'; + emit('ready', { channelId: channelId }); + break; + case 'message_sent': + emit('message_sent', { + channelId: channelId, + sessionId: e.data.session_id, + query: e.data.query, + }); + break; + case 'message_received': + emit('message_received', { + channelId: channelId, + sessionId: e.data.session_id, + content: e.data.content, + }); + break; + default: + break; + } + } + + function setOpen(next) { + panelOpen = !!next; + panel.style.display = panelOpen ? 'block' : 'none'; + launcher.textContent = panelOpen ? '✕' : '💬'; + if (panelOpen) { + emit('open', { channelId: channelId }); + } else { + emit('close', { channelId: channelId }); + } + } + + function open() { setOpen(true); } + function close() { setOpen(false); } + function toggle() { setOpen(!panelOpen); } + + function destroy() { + if (destroyed) return; + destroyed = true; + if (refreshTimer) clearTimeout(refreshTimer); + global.removeEventListener('message', onMessage); + if (launcher.parentNode) launcher.parentNode.removeChild(launcher); + if (panel.parentNode) panel.parentNode.removeChild(panel); + listeners = {}; + if (instance === api) instance = null; + } + + launcher.addEventListener('click', toggle); + iframe.addEventListener('load', function () { + // The embed page lives at embedOrigin; we cannot (and need not) read the + // cross-origin contentWindow.location. Just (re)provide the token. + iframeOrigin = embedOrigin; + provideToken(); + }); + + document.body.appendChild(launcher); + document.body.appendChild(panel); + global.addEventListener('message', onMessage); + + return { + open: open, + close: close, + toggle: toggle, + destroy: destroy, + isOpen: function () { return panelOpen; }, + isReady: function () { return iframeReady; }, + setContext: setContext, + openWithQuery: openWithQuery, + setLocale: setLocale, + }; + } + + var api = { + init: function (opts) { + if (instance) instance.destroy(); + instance = createWidget(opts || {}); + return instance; + }, + open: function () { if (instance) instance.open(); }, + close: function () { if (instance) instance.close(); }, + toggle: function () { if (instance) instance.toggle(); }, + destroy: function () { if (instance) instance.destroy(); }, + on: function (event, handler) { + if (!handler || typeof handler !== 'function') return; + if (!listeners[event]) listeners[event] = []; + listeners[event].push(handler); + }, + off: function (event, handler) { + if (!listeners[event]) return; + if (!handler) { + delete listeners[event]; + return; + } + listeners[event] = listeners[event].filter(function (fn) { return fn !== handler; }); + }, + setContext: function (ctx) { if (instance) instance.setContext(ctx); }, + openWithQuery: function (query) { if (instance) instance.openWithQuery(query); }, + setLocale: function (locale) { if (instance) instance.setLocale(locale); }, + }; + + global.WeKnora = api; + + var legacyScript = document.currentScript; + if (legacyScript) { + var legacyChannel = legacyScript.getAttribute('data-channel'); + var legacyToken = legacyScript.getAttribute('data-token'); + var legacyTokenEndpoint = legacyScript.getAttribute('data-token-endpoint'); + if (legacyChannel && (legacyToken || legacyTokenEndpoint)) { + api.init({ + channel: legacyChannel, + token: legacyToken, + tokenEndpoint: legacyTokenEndpoint, + scriptEl: legacyScript, + position: legacyScript.getAttribute('data-position'), + primaryColor: legacyScript.getAttribute('data-primary-color'), + title: legacyScript.getAttribute('data-title'), + baseUrl: legacyScript.getAttribute('data-base-url'), + width: legacyScript.getAttribute('data-width'), + height: legacyScript.getAttribute('data-height'), + }); + } + } +})(typeof window !== 'undefined' ? window : this); diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index 4dbf23e9..1104f55e 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -35,7 +35,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[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; method: string; url: string }) => { + const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: 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 }) => { // 重置状态 output.value = ''; error.value = null; @@ -45,8 +45,8 @@ export function useStream() { // 获取API配置 const apiUrl = getApiBaseUrl(); - // 获取JWT Token - const token = localStorage.getItem('weknora_token'); + const embedToken = params.embed_token; + const token = embedToken || localStorage.getItem('weknora_token'); if (!token) { error.value = i18n.global.t('error.tokenNotFound'); stopStream(); @@ -63,13 +63,6 @@ export function useStream() { const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id'); const tenantIdHeader: string | null = selectedTenantId || null; - // Validate knowledge_base_ids for agent-chat requests - // Note: knowledge_base_ids can be empty if user hasn't selected any, but we allow it - // The backend will handle the case when no knowledge bases are selected - const isAgentChat = params.url === '/api/v1/agent-chat'; - // Removed validation - allow empty knowledge_base_ids array - // The backend should handle this case appropriately - // TTFB instrumentation: record the moment we kick off the request so // we can compare it with the first answer chunk we receive from the // server. This makes it possible to correlate the frontend-observed @@ -132,7 +125,7 @@ export function useStream() { if (params.attachment_uploads !== undefined && params.attachment_uploads.length > 0) { postBody.attachment_uploads = params.attachment_uploads; } - postBody.channel = "web"; + postBody.channel = embedToken ? "embed" : "web"; lastStreamRequest.value = { requestId: requestID, @@ -146,10 +139,11 @@ export function useStream() { method: params.method, headers: { "Content-Type": "application/json", - "Authorization": `Bearer ${token}`, + "Authorization": embedToken ? `Embed ${embedToken}` : `Bearer ${token}`, "Accept-Language": i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN', "X-Request-ID": requestID, - ...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}), + ...(!embedToken && tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}), + ...(params.embed_session_sig ? { "X-Embed-Session": params.embed_session_sig } : {}), }, body: params.method == "POST" diff --git a/frontend/src/api/embed/index.ts b/frontend/src/api/embed/index.ts new file mode 100644 index 00000000..2a75354a --- /dev/null +++ b/frontend/src/api/embed/index.ts @@ -0,0 +1,516 @@ +import { get, post, put, del } from '@/utils/request' +import { resolveEmbedBaseUrl } from '@/utils/embedBaseUrl' + +export interface EmbedChannel { + id: string + tenant_id: number + agent_id: string + name: string + enabled: boolean + allowed_origins: string[] + welcome_message: string + rate_limit_per_minute: number + rate_limit_per_day?: number + primary_color?: string + page_title?: string + header_title_mode?: HeaderTitleMode + show_suggested_questions?: boolean + widget_position?: WidgetPosition + allow_web_search?: boolean + allow_memory?: boolean + allow_file_upload?: boolean + default_locale?: string + webhook_url?: string + has_webhook_secret?: boolean + publish_token?: string + created_at: string + updated_at: string +} + +export interface EmbedChannelPublicConfig { + channel_id: string + name: string + display_title?: string + knowledge_base_ids?: string[] + agent_id: string + agent_name?: string + agent_avatar?: string + welcome_message: string + primary_color?: string + page_title?: string + header_title_mode?: HeaderTitleMode + show_suggested_questions?: boolean + widget_position?: WidgetPosition + allow_web_search?: boolean + allow_memory?: boolean + allow_file_upload?: boolean + agent_web_search_enabled?: boolean + agent_image_upload_enabled?: boolean + default_locale?: string +} + +export type EmbedLocaleTag = 'zh-CN' | 'en-US' | 'ko-KR' | 'ru-RU' | '' + +export interface EmbedChannelStats { + session_count: number +} + +export type HeaderTitleMode = 'channel' | 'session' +export type WidgetPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' + +/** Prefix of short-lived embed session tokens minted by the backend. */ +export const EMBED_SESSION_TOKEN_PREFIX = 'ems_' + +/** Whether a token is already a short-lived session token (secure mode). */ +export function isEmbedSessionToken(token: string): boolean { + return typeof token === 'string' && token.trim().startsWith(EMBED_SESSION_TOKEN_PREFIX) +} + +export async function listEmbedChannels(agentId: string) { + return get<{ success: boolean; data: EmbedChannel[] }>(`/api/v1/agents/${agentId}/embed-channels`) +} + +export async function listAllEmbedChannels() { + return get<{ success: boolean; data: EmbedChannel[] }>('/api/v1/embed-channels') +} + +export async function createEmbedChannel(agentId: string, data: Partial) { + return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/agents/${agentId}/embed-channels`, data) +} + +export async function updateEmbedChannel(channelId: string, data: Partial) { + return put<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}`, data) +} + +export async function deleteEmbedChannel(channelId: string) { + return del(`/api/v1/embed-channels/${channelId}`) +} + +export async function rotateEmbedToken(channelId: string) { + return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}/rotate-token`, {}) +} + +/** Short-lived session token for management UI preview (JWT auth, no publish token needed). */ +export async function getEmbedChannelStats(channelId: string) { + return get<{ success: boolean; data: EmbedChannelStats }>( + `/api/v1/embed-channels/${channelId}/stats`, + ) +} + +export async function issueEmbedPreviewSession(channelId: string) { + return post<{ success: boolean; data: { session_token: string; expires_in: number } }>( + `/api/v1/embed-channels/${channelId}/preview-session`, + {}, + ) +} + +export interface SuggestedQuestion { + question: string + source?: string +} + +export async function getEmbedChunkById(channelId: string, token: string, chunkId: string) { + return get<{ success: boolean; data: { content?: string } }>( + `/api/v1/embed/${channelId}/chunks/${chunkId}`, + { headers: { Authorization: `Embed ${token}` } }, + ) +} + +export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit = 6) { + return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>( + `/api/v1/embed/${channelId}/suggested-questions?limit=${limit}`, + { headers: { Authorization: `Embed ${token}` } }, + ) +} + +export async function getEmbedConfig(channelId: string, token: string) { + return get<{ success: boolean; data: EmbedChannelPublicConfig }>( + `/api/v1/embed/${channelId}/config`, + { headers: { Authorization: `Embed ${token}` } }, + ) +} + +export async function createEmbedSession(channelId: string, token: string) { + return post<{ success: boolean; data: { id: string; sig: string } }>( + `/api/v1/embed/${channelId}/sessions`, + {}, + { headers: { Authorization: `Embed ${token}` } }, + ) +} + +export async function exchangeEmbedSession(channelId: string, publishToken: string) { + return post<{ success: boolean; data: { session_token: string; expires_in: number } }>( + `/api/v1/embed/${channelId}/exchange`, + {}, + { headers: { Authorization: `Embed ${publishToken}` } }, + ) +} + +export async function stopEmbedSession( + channelId: string, + token: string, + sessionId: string, + messageId: string, + sessionSig: string, +) { + const headers: Record = { + Authorization: `Embed ${token}`, + 'X-Embed-Session': sessionSig, + } + return post(`/api/v1/embed/${channelId}/sessions/${sessionId}/stop`, { message_id: messageId }, { headers }) +} + +export async function getEmbedMessageList( + channelId: string, + token: string, + sessionId: string, + limit: number, + beforeTime?: string, + sig?: string, +) { + const params = new URLSearchParams({ limit: String(limit) }) + if (beforeTime) { + params.set('before_time', beforeTime) + } + const headers: Record = { Authorization: `Embed ${token}` } + // Signed session handle — sent as a header so it never lands in URL/access logs. + if (sig) headers['X-Embed-Session'] = sig + return get<{ success: boolean; data: unknown[] }>( + `/api/v1/embed/${channelId}/messages/${sessionId}/load?${params.toString()}`, + { headers }, + ) +} + +const EMBED_MSG_SOURCE = 'weknora-embed' +const EMBED_HOST_SOURCE = 'weknora-host' + +// The exact parent origin, learned from the first trusted host message +// (trust-on-first-use). Once known, every inbound/outbound message is pinned to +// it so conversation content is never broadcast to an unexpected window. +let verifiedParentOrigin = '' + +function referrerParentOrigin(): string { + if (window.parent === window) return '' + try { + if (document.referrer) { + return new URL(document.referrer).origin + } + } catch { + // ignore malformed referrer + } + return '' +} + +/** Best-known parent origin: verified handshake first, then referrer. */ +function knownParentOrigin(): string { + return verifiedParentOrigin || referrerParentOrigin() +} + +function isTrustedParentMessage(event: MessageEvent): boolean { + if (window.parent === window) return false + if (event.source !== window.parent) return false + if (!event.data || event.data.source !== EMBED_HOST_SOURCE) return false + if (typeof event.origin !== 'string' || event.origin === 'null') return false + const expected = knownParentOrigin() + if (expected) { + if (event.origin !== expected) return false + } else { + // First trusted handshake with no referrer hint: pin to this origin. + verifiedParentOrigin = event.origin + } + return true +} + +/** + * Post a message to the host page. + * `sensitive` payloads (conversation content) are dropped when the parent + * origin is unknown rather than broadcast to '*'. Non-sensitive handshake + * messages (bootstrap_request/ready) may fall back to '*' so token handoff can + * still bootstrap when the referrer is stripped. + */ +function postToParent(payload: Record, opts?: { sensitive?: boolean }) { + if (window.parent === window) return + const target = knownParentOrigin() + if (!target) { + if (opts?.sensitive) return + window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, '*') + return + } + window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, target) +} + +/** Notify the parent page that the embed widget is ready. */ +export function postEmbedReady(channelId: string) { + postToParent({ type: 'ready', channel_id: channelId }) +} + +/** Request a publish token from the parent host page. */ +export function postEmbedBootstrapRequest(channelId: string) { + postToParent({ type: 'bootstrap_request', channel_id: channelId }) +} + +/** Notify the parent page when a user message is sent. */ +export function postEmbedMessageSent(channelId: string, sessionId: string, query: string) { + postToParent( + { + type: 'message_sent', + channel_id: channelId, + session_id: sessionId, + query, + }, + { sensitive: true }, + ) +} + +/** Relay a chat event to the channel webhook (server-side, best-effort). */ +export function relayEmbedWebhookEvent( + channelId: string, + token: string, + sessionId: string, + sessionSig: string, + body: { type: 'message_sent' | 'message_received'; query?: string; content?: string }, +) { + const headers: Record = { + Authorization: `Embed ${token}`, + 'X-Embed-Session': sessionSig, + } + void post( + `/api/v1/embed/${channelId}/sessions/${sessionId}/events`, + { type: body.type, session_id: sessionId, query: body.query, content: body.content }, + { headers }, + ).catch(() => { + // Webhook relay must not block chat. + }) +} + +/** Notify the parent page when an assistant reply completes. */ +export function postEmbedMessageReceived(channelId: string, sessionId: string, content: string) { + postToParent( + { + type: 'message_received', + channel_id: channelId, + session_id: sessionId, + content, + }, + { sensitive: true }, + ) +} + +export function parseEmbedTokenFromLocation(): string { + const queryToken = new URLSearchParams(window.location.search).get('token') + if (queryToken) return queryToken + + const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : '' + if (!hash) return '' + return new URLSearchParams(hash).get('token') || '' +} + +export function buildEmbedURL( + channelId: string, + token?: string, + opts?: { locale?: string; refreshKey?: number; baseUrl?: string }, +) { + const base = safeBaseUrl(opts?.baseUrl) || resolveEmbedBaseUrl() + let path = `${base}/embed/${encodeURIComponent(channelId)}` + const params = new URLSearchParams() + if (opts?.locale?.trim()) params.set('locale', opts.locale.trim()) + if (opts?.refreshKey) params.set('r', String(opts.refreshKey)) + const qs = params.toString() + if (qs) path += `?${qs}` + if (token) path += `#token=${encodeURIComponent(token)}` + return path +} + +/** Escape a value for safe interpolation inside an HTML double-quoted attribute. */ +function escapeHtmlAttr(value: string): string { + return String(value) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>') +} + +/** Validate that a base URL is a well-formed http(s) origin; fall back otherwise. */ +function safeBaseUrl(raw?: string): string { + const fallback = window.location.origin + if (!raw) return fallback + try { + const u = new URL(raw, window.location.href) + if (u.protocol !== 'http:' && u.protocol !== 'https:') return fallback + return u.origin + } catch { + return fallback + } +} + +export function buildEmbedSnippet(channelId: string, token?: string) { + // A bare iframe has no token-handoff host, so the snippet must carry the + // publish token in the URL hash, otherwise the embed page cannot bootstrap. + const url = escapeHtmlAttr(buildEmbedURL(channelId, token)) + return `` +} + +export function buildWidgetSnippet( + channelId: string, + token: string, + opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string }, +) { + const base = safeBaseUrl(opts?.baseUrl) + const position = opts?.position || 'bottom-right' + const attrs = [ + `src="${escapeHtmlAttr(`${base}/weknora-widget.js`)}"`, + `data-channel="${escapeHtmlAttr(channelId)}"`, + `data-token="${escapeHtmlAttr(token)}"`, + `data-position="${escapeHtmlAttr(position)}"`, + ] + if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`) + if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`) + // Cross-origin embed: add data-sandbox="true" when using a dedicated embed subdomain. + return `` +} + +/** Default placeholder for the integrator's own token-minting endpoint. */ +export const SECURE_TOKEN_ENDPOINT_PLACEHOLDER = 'https://your-backend.example.com/weknora/embed-token' + +/** + * Secure-mode widget snippet: the page references an endpoint on the + * integrator's own backend (data-token-endpoint) instead of carrying the + * publish token. The publish token never reaches the browser. + */ +export function buildSecureWidgetSnippet( + channelId: string, + opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string; tokenEndpoint?: string }, +) { + const base = safeBaseUrl(opts?.baseUrl) + const position = opts?.position || 'bottom-right' + const endpoint = opts?.tokenEndpoint || SECURE_TOKEN_ENDPOINT_PLACEHOLDER + const attrs = [ + `src="${escapeHtmlAttr(`${base}/weknora-widget.js`)}"`, + `data-channel="${escapeHtmlAttr(channelId)}"`, + `data-token-endpoint="${escapeHtmlAttr(endpoint)}"`, + `data-position="${escapeHtmlAttr(position)}"`, + ] + if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`) + if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`) + return `` +} + +/** + * Server-side reference (Node/Express) for the token-minting endpoint that + * secure mode points at. The publish token stays on the server; the endpoint + * exchanges it for a short-lived session token and returns that to the page. + */ +export function buildSecureServerNodeExample(channelId: string, opts?: { baseUrl?: string }) { + const base = safeBaseUrl(opts?.baseUrl) + const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange` + return [ + `// Node/Express — keep WEKNORA_PUBLISH_TOKEN only on the server (env var).`, + `app.get('/weknora/embed-token', async (req, res) => {`, + ` // Only mint for logged-in visitors — e.g. session cookie or Bearer token.`, + ` const auth = req.headers.authorization || ''`, + ` const hasSession = Boolean(req.cookies?.session_id)`, + ` if (!hasSession && !auth.startsWith('Bearer ')) {`, + ` return res.status(401).json({ error: 'unauthorized' })`, + ` }`, + ` const r = await fetch('${exchangeUrl}', {`, + ` method: 'POST',`, + ` headers: {`, + ` Authorization: 'Embed ' + process.env.WEKNORA_PUBLISH_TOKEN,`, + ` Origin: 'https://your-site.example.com', // must match channel allowed_origins`, + ` },`, + ` })`, + ` const body = await r.json()`, + ` if (!body?.data?.session_token) return res.status(502).json({ error: 'mint failed' })`, + ` res.json({ token: body.data.session_token, expiresIn: body.data.expires_in })`, + `})`, + ].join('\n') +} + +export function buildSecureServerGoExample(channelId: string, opts?: { baseUrl?: string }) { + const base = safeBaseUrl(opts?.baseUrl) + const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange` + return [ + `// Go net/http — keep WEKNORA_PUBLISH_TOKEN only on the server (env var).`, + `func embedTokenHandler(w http.ResponseWriter, r *http.Request) {`, + ` if r.Header.Get("Authorization") == "" && r.Header.Get("Cookie") == "" {`, + ` http.Error(w, \`{"error":"unauthorized"}\`, http.StatusUnauthorized)`, + ` return`, + ` }`, + ` req, _ := http.NewRequest(http.MethodPost, "${exchangeUrl}", nil)`, + ` req.Header.Set("Authorization", "Embed "+os.Getenv("WEKNORA_PUBLISH_TOKEN"))`, + ` req.Header.Set("Origin", "https://your-site.example.com") // must match channel allowed_origins`, + ` resp, err := http.DefaultClient.Do(req)`, + ` if err != nil || resp.StatusCode >= 300 {`, + ` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`, + ` return`, + ` }`, + ` defer resp.Body.Close()`, + ` var body struct { Data struct { SessionToken string \`json:"session_token"\` ExpiresIn int \`json:"expires_in"\` } \`json:"data"\` }`, + ` if json.NewDecoder(resp.Body).Decode(&body) != nil || body.Data.SessionToken == "" {`, + ` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`, + ` return`, + ` }`, + ` w.Header().Set("Content-Type", "application/json")`, + ` json.NewEncoder(w).Encode(map[string]any{"token": body.Data.SessionToken, "expiresIn": body.Data.ExpiresIn})`, + `}`, + ].join('\n') +} + +/** @deprecated Use buildSecureServerNodeExample */ +export function buildSecureServerExample(channelId: string, opts?: { baseUrl?: string }) { + return buildSecureServerNodeExample(channelId, opts) +} + +export function buildSecureServerExamples(channelId: string, opts?: { baseUrl?: string }) { + return [ + buildSecureServerNodeExample(channelId, opts), + '', + buildSecureServerGoExample(channelId, opts), + ].join('\n') +} + +/** Listen for context injected by the parent page (embed host). */ +export function onEmbedHostContext(handler: (payload: Record) => void) { + const listener = (e: MessageEvent) => { + if (!isTrustedParentMessage(e) || e.data.type !== 'set_context') return + handler(e.data.payload || {}) + } + window.addEventListener('message', listener) + return () => window.removeEventListener('message', listener) +} + +/** Listen for a publish token provided by the parent host page. */ +export function onEmbedHostToken(handler: (token: string, channelId?: string) => void) { + const listener = (e: MessageEvent) => { + if (!isTrustedParentMessage(e) || e.data.type !== 'provide_token') return + const token = String(e.data.token || '').trim() + if (!token) return + handler(token, e.data.channel_id) + } + window.addEventListener('message', listener) + return () => window.removeEventListener('message', listener) +} + +/** Listen for locale changes from the parent host page. */ +export function onEmbedHostLocale(handler: (locale: string) => void) { + const listener = (e: MessageEvent) => { + if (!isTrustedParentMessage(e) || e.data.type !== 'set_locale') return + const locale = String(e.data.payload?.locale || e.data.locale || '').trim() + if (!locale) return + handler(locale) + } + window.addEventListener('message', listener) + return () => window.removeEventListener('message', listener) +} + +/** Listen for a pre-filled query from the parent host page. */ +export function onEmbedHostOpenWithQuery(handler: (query: string) => void) { + const listener = (e: MessageEvent) => { + if (!isTrustedParentMessage(e) || e.data.type !== 'open_with_query') return + const query = String(e.data.payload?.query || e.data.query || '').trim() + if (!query) return + handler(query) + } + window.addEventListener('message', listener) + return () => window.removeEventListener('message', listener) +} diff --git a/frontend/src/components/AgentEmbedChannelPanel.vue b/frontend/src/components/AgentEmbedChannelPanel.vue new file mode 100644 index 00000000..37408d40 --- /dev/null +++ b/frontend/src/components/AgentEmbedChannelPanel.vue @@ -0,0 +1,1565 @@ + + + + + diff --git a/frontend/src/components/EmbedChannelPreview.vue b/frontend/src/components/EmbedChannelPreview.vue new file mode 100644 index 00000000..7a3be14d --- /dev/null +++ b/frontend/src/components/EmbedChannelPreview.vue @@ -0,0 +1,325 @@ +