| 123456789101112131415161718192021222324252627282930313233343536 |
- // 业务平台后端示例(无依赖):提供构建好的前端,并用 API Key 为浏览器换取短期令牌。
- // API Key 只存在于后端环境变量中,浏览器拿到的是 1 小时有效的浏览器令牌。
- // 真实平台应先校验自己的登录态(只给已登录用户签发令牌)。
- 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 PORT = Number(process.env.PORT ?? 5180)
- const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), 'dist')
- if (!AGENT_API_KEY) throw new Error('请设置环境变量 AGENT_API_KEY')
- const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' }
- http.createServer(async (req, res) => {
- if (req.method === 'POST' && req.url === '/api/agent-token') {
- // 在这里校验平台自己的登录态
- const r = await fetch(`${AGENT_SERVER_URL}/v1/browser-tokens`, {
- method: 'POST',
- headers: { authorization: `Bearer ${AGENT_API_KEY}`, '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 }))
- }
- 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})`))
|