54 lines
1.6 KiB
JavaScript
54 lines
1.6 KiB
JavaScript
export function json(res, status, payload) {
|
|
const body = JSON.stringify(payload)
|
|
res.writeHead(status, {
|
|
'content-type': 'application/json; charset=utf-8',
|
|
'cache-control': 'no-store',
|
|
'content-length': Buffer.byteLength(body)
|
|
})
|
|
res.end(body)
|
|
}
|
|
|
|
/** 只从本机 loopback 和同源页面进来的请求才放行:挡住 DNS rebinding 与跨站 POST。 */
|
|
export function guard(req) {
|
|
const host = String(req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^\[|\]$/g, '')
|
|
const local = host === '127.0.0.1' || host === 'localhost' || host === '::1' || host.endsWith('.localhost')
|
|
if (!local) return '只接受来自本机的请求'
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
const origin = req.headers.origin
|
|
if (!origin) return '缺少 Origin 头'
|
|
let ok = false
|
|
try {
|
|
ok = new URL(origin).host.toLowerCase() === String(req.headers.host || '').toLowerCase()
|
|
} catch {
|
|
ok = false
|
|
}
|
|
if (!ok) return '跨站请求被拒绝'
|
|
}
|
|
return null
|
|
}
|
|
|
|
export function readJson(req, limit = 64 * 1024) {
|
|
return new Promise((resolve, reject) => {
|
|
let size = 0
|
|
const chunks = []
|
|
req.on('data', (chunk) => {
|
|
size += chunk.length
|
|
if (size > limit) {
|
|
reject(new Error('请求体太大'))
|
|
req.destroy()
|
|
return
|
|
}
|
|
chunks.push(chunk)
|
|
})
|
|
req.on('end', () => {
|
|
try {
|
|
const text = Buffer.concat(chunks).toString('utf8').trim()
|
|
resolve(text ? JSON.parse(text) : {})
|
|
} catch (error) {
|
|
reject(new Error('请求体不是合法 JSON'))
|
|
}
|
|
})
|
|
req.on('error', reject)
|
|
})
|
|
}
|