import type { Plugin } from 'vite'; import fs from 'fs'; import path from 'path'; import { MAKE_CONFIG_RELATIVE_PATH } from './utils/makeConstants'; export function lanAccessControlPlugin(): Plugin { let allowLAN = true; return { name: 'lan-access-control', configResolved() { const configPath = path.resolve(process.cwd(), MAKE_CONFIG_RELATIVE_PATH); if (fs.existsSync(configPath)) { try { const axhubConfig = JSON.parse(fs.readFileSync(configPath, 'utf8')); allowLAN = axhubConfig.server?.allowLAN !== false; console.log(`🔒 局域网访问控制: ${allowLAN ? '允许' : '禁止'}`); } catch { // Ignore config parse errors and keep default. } } }, configureServer(server: any) { server.middlewares.use((req: any, res: any, next: any) => { if (allowLAN) { return next(); } const clientIP = req.socket.remoteAddress || req.connection.remoteAddress; const localIPs = [ '127.0.0.1', '::1', '::ffff:127.0.0.1', 'localhost', ]; const isLocalAccess = localIPs.some((ip) => clientIP?.includes(ip)); if (!isLocalAccess) { res.statusCode = 403; res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(`
此服务器已禁用局域网访问。
只允许本地访问(localhost/127.0.0.1)。
如需允许局域网访问,请在配置文件中设置 allowLAN: true 并重启服务器