Files
zyt/admin/local-preview/server.mjs
T

85 lines
5.9 KiB
JavaScript

// A loopback static/fixture server. No proxy, database driver, transport client or environment credentials.
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const dist = fileURLToPath(new URL('../node_modules/.zyt-ui-preview/dist/', import.meta.url))
const host = '127.0.0.1'
const demoPort = 5180, entryPort = 5178
const demoOrigin = `http://${host}:${demoPort}`, entryAuthority = `${host}:${entryPort}`
const entryDestination = 'http://127.0.0.1:5179/admin/#'
// This listener serves no bytes from disk and has no transport to 5179.
// An explicit empty fragment prevents browsers carrying an old fragment into 5179.
export function serveOldEntry(req, res) {
res.setHeader('Cache-Control', 'no-store')
res.setHeader('Referrer-Policy', 'no-referrer')
res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'; base-uri 'none'")
const end = (status, headers) => { res.writeHead(status, headers); res.end() }
const h = req.headers
if (h.host !== entryAuthority || (h.origin && h.origin !== 'http://' + entryAuthority) || h['sec-fetch-site'] === 'cross-site') return end(403)
if (req.method !== 'GET') return end(405, {Allow:'GET'})
if ((h['sec-fetch-mode'] && h['sec-fetch-mode'] !== 'navigate') ||
(h['sec-fetch-dest'] && h['sec-fetch-dest'] !== 'document') ||
(h.accept && !/(?:^|,)\s*(?:text\/html|\*\/\*)(?:[;,]|$)/i.test(h.accept)) ||
h.authorization || h.token) return end(403)
const pathname = req.url?.split('?', 1)[0]
if (pathname !== '/' && !/^\/admin(?:\/[a-zA-Z0-9_-]+)*\/?$/.test(pathname)) return end(404)
if (/(?:^|\/)(?:assets|static|adminapi|api|api-proxy|proxy)(?:\/|$)/i.test(pathname)) return end(404)
return end(302, {Location:entryDestination})
}
// The fixture module is deliberately loaded only on explicit demo startup.
async function createDemoHandler() {
const { resolveFixture } = await import('./fixtures.mjs')
await readFile(path.join(dist,'local-preview/index.html'))
return async (req, res) => serveDemo(resolveFixture, req, res)
}
const csp = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'none'; frame-src 'none'; worker-src 'none'; form-action 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
const types = {'.js':'application/javascript','.css':'text/css','.svg':'image/svg+xml','.woff2':'font/woff2','.woff':'font/woff','.png':'image/png','.jpg':'image/jpeg','.webp':'image/webp','.gif':'image/gif','.ttf':'font/ttf'}
const routes = new Set(['/','/admin','/admin/','/admin/workbench','/admin/order','/admin/members','/admin/members/detail','/admin/appointments','/admin/roster','/admin/dept-stats'])
async function serveDemo(resolveFixture,req,res) {
res.setHeader('Content-Security-Policy',csp); res.setHeader('Cache-Control','no-store'); res.setHeader('X-Content-Type-Options','nosniff'); res.setHeader('Referrer-Policy','no-referrer')
const send=(status,type,body)=>{ res.writeHead(status,{'Content-Type':type}); res.end(req.method==='HEAD' ? undefined : body) }
const json=(status,obj)=>send(status,'application/json; charset=utf-8',JSON.stringify(obj))
const deny=(status)=>json(status,{code:0,show:1,msg:'本地只读预览:此操作未开放',data:null})
if(req.headers.host !== `${host}:${demoPort}` || (req.headers.origin && req.headers.origin !== demoOrigin) || req.headers['sec-fetch-site']==='cross-site') return deny(403)
if(!req.url?.startsWith('/') || req.url.startsWith('//')) return deny(400)
const {pathname,searchParams}=new URL(req.url,demoOrigin)
if(pathname.startsWith('/adminapi/')) {
let params=Object.fromEntries(searchParams)
if(pathname==='/adminapi/order.order/detail') {
if(req.method!=='POST') return deny(405)
if(!req.headers['content-type']?.startsWith('application/json')) return deny(415)
let raw=''; for await(const chunk of req){ raw+=chunk; if(raw.length>4096) return deny(413) }
try { params=JSON.parse(raw); if(!params || typeof params!=='object' || Array.isArray(params)) return deny(400) } catch { return deny(400) }
} else if(req.method!=='GET') return deny(405)
const result=resolveFixture(pathname,params); return result ? json(200,result) : deny(403)
}
if(!['GET','HEAD'].includes(req.method)) return deny(405)
if(routes.has(pathname)) return send(200,'text/html; charset=utf-8',await readFile(path.join(dist,'local-preview/index.html')))
const asset=pathname.match(/^\/admin\/assets\/([a-zA-Z0-9_.-]+)$/)
if(asset && types[path.extname(asset[1])]) {
try { return send(200,types[path.extname(asset[1])],await readFile(path.join(dist,'assets',asset[1]))) } catch { return deny(404) }
}
return deny(404)
}
function selectPort(args) {
if (args.length === 0 || (args.length === 1 && args[0] === String(entryPort))) return entryPort
if (args.length === 1 && args[0] === String(demoPort)) return demoPort
throw new Error('端口仅支持 5178(旧入口跳转)或 5180(合成数据演示)')
}
export async function createLocalListener(args) {
const port = selectPort(args)
const handler = port === demoPort ? await createDemoHandler() : serveOldEntry
return {port, handler}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const {port, handler} = await createLocalListener(process.argv.slice(2))
const label = port === demoPort ? `合成数据演示:${demoOrigin}/admin/workbench` : `旧入口仅跳转到正式数据查询:${entryDestination}`
http.createServer(async (req, res) => {
try { await handler(req, res) }
catch { if (!res.headersSent) res.writeHead(500); res.end() }
}).listen(port, host, () => console.log(label))
}