| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- // 业务平台后端示例(无依赖):提供构建好的前端,并用 Key 为浏览器换取短期令牌。
- // Key 只存在于后端环境变量中,浏览器拿到的是 1 小时有效的浏览器令牌:
- // AGENT_API_KEY → /v1(单个助手的对话),AGENT_BOT_KEY → /bot/v1(机器人工作组),至少设置一个。
- // 真实平台应先校验自己的登录态(只给已登录用户签发令牌)。
- import fs from 'node:fs'
- import http from 'node:http'
- import path from 'node:path'
- import { fileURLToPath } from 'node:url'
- const AGENT_SERVER_URL = process.env.AGENT_SERVER_URL ?? 'http://127.0.0.1:8787'
- const AGENT_API_KEY = process.env.AGENT_API_KEY
- const AGENT_BOT_KEY = process.env.AGENT_BOT_KEY
- const PORT = Number(process.env.PORT ?? 5180)
- const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), 'dist')
- if (!AGENT_API_KEY && !AGENT_BOT_KEY) throw new Error('请设置环境变量 AGENT_API_KEY 和 / 或 AGENT_BOT_KEY')
- const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' }
- const tokenEndpoints = {
- '/api/agent-token': [AGENT_API_KEY, '/v1/browser-tokens'],
- '/api/bot-token': [AGENT_BOT_KEY, '/bot/v1/browser-tokens'],
- }
- http.createServer(async (req, res) => {
- const endpoint = req.method === 'POST' && tokenEndpoints[req.url]
- if (endpoint && endpoint[0]) {
- // 在这里校验平台自己的登录态
- const r = await fetch(`${AGENT_SERVER_URL}${endpoint[1]}`, {
- method: 'POST',
- headers: { authorization: `Bearer ${endpoint[0]}`, 'content-type': 'application/json' },
- body: JSON.stringify({ ttlSeconds: 3600 }),
- })
- res.writeHead(r.status, { 'content-type': 'application/json' })
- return res.end(await r.text())
- }
- if (req.url === '/api/config') {
- res.writeHead(200, { 'content-type': 'application/json' })
- return res.end(JSON.stringify({ agentServerUrl: process.env.AGENT_SERVER_PUBLIC_URL ?? AGENT_SERVER_URL, chat: !!AGENT_API_KEY, teams: !!AGENT_BOT_KEY }))
- }
- const file = path.join(dist, path.normalize(decodeURIComponent(req.url.split('?')[0])).replace(/^(\.\.[/\\])+/, ''))
- const target = fs.existsSync(file) && fs.statSync(file).isFile() ? file : path.join(dist, 'index.html')
- res.writeHead(200, { 'content-type': types[path.extname(target)] ?? 'application/octet-stream' })
- fs.createReadStream(target).pipe(res)
- }).listen(PORT, '127.0.0.1', () => console.log(`示例平台:http://127.0.0.1:${PORT}(AgentServer:${AGENT_SERVER_URL})`))
|