import { timingSafeEqual } from 'node:crypto' /** * 可选的访问密码(HTTP Basic Auth)。 * 设置环境变量 NOVEL_PASSWORD 后启用,用户名任意;本机使用可以不设置。 */ export default defineEventHandler((event) => { const password = process.env.NOVEL_PASSWORD if (!password) return const header = getHeader(event, 'authorization') || '' if (header.startsWith('Basic ')) { const decoded = Buffer.from(header.slice(6), 'base64').toString('utf8') const given = Buffer.from(decoded.slice(decoded.indexOf(':') + 1)) const expected = Buffer.from(password) if (given.length === expected.length && timingSafeEqual(given, expected)) return } setHeader(event, 'WWW-Authenticate', 'Basic realm="AI Novel Studio", charset="UTF-8"') throw createError({ statusCode: 401, message: '需要访问密码' }) })