352 lines
14 KiB
JavaScript
352 lines
14 KiB
JavaScript
// 极简图床:零依赖,node server.mjs 就能跑。
|
||
// 文件存在 data/images/YYYY/MM/,缩略图在 data/thumbs/,索引是 data/index.json。
|
||
import { createServer } from 'node:http'
|
||
import { createHash, randomBytes } from 'node:crypto'
|
||
import { mkdir, readFile, writeFile, rename, stat, unlink, readdir, rm } from 'node:fs/promises'
|
||
import { createReadStream } from 'node:fs'
|
||
import { extname, join, normalize, resolve, sep } from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
|
||
const ROOT = fileURLToPath(new URL('.', import.meta.url))
|
||
const DATA = join(ROOT, 'data')
|
||
const IMAGES = join(DATA, 'images')
|
||
const THUMBS = join(DATA, 'thumbs')
|
||
const INDEX = join(DATA, 'index.json')
|
||
const CONFIG = join(DATA, 'config.json')
|
||
const PUBLIC = join(ROOT, 'public')
|
||
|
||
const PORT = Number(process.env.PORT || 8095)
|
||
const HOST = process.env.HOST || '0.0.0.0'
|
||
const MAX_BYTES = 25 * 1024 * 1024
|
||
const MIME = {
|
||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp',
|
||
'.gif': 'image/gif', '.avif': 'image/avif', '.svg': 'image/svg+xml', '.bmp': 'image/bmp',
|
||
}
|
||
const ALLOWED = new Set(Object.keys(MIME))
|
||
|
||
let config = { token: '' }
|
||
let index = { images: [] }
|
||
let saving = Promise.resolve()
|
||
|
||
// ---------- 存储 ----------
|
||
|
||
const json = async (path, fallback) => {
|
||
try {
|
||
return JSON.parse(await readFile(path, 'utf8'))
|
||
} catch {
|
||
return fallback
|
||
}
|
||
}
|
||
|
||
async function saveIndex() {
|
||
saving = saving.then(async () => {
|
||
const tmp = `${INDEX}.tmp`
|
||
await writeFile(tmp, JSON.stringify(index, null, 2))
|
||
await rename(tmp, INDEX)
|
||
})
|
||
return saving
|
||
}
|
||
|
||
async function boot() {
|
||
await mkdir(IMAGES, { recursive: true })
|
||
await mkdir(THUMBS, { recursive: true })
|
||
config = await json(CONFIG, null)
|
||
if (!config?.token) {
|
||
config = { token: randomBytes(18).toString('hex'), createdAt: new Date().toISOString() }
|
||
await writeFile(CONFIG, JSON.stringify(config, null, 2), { mode: 0o600 })
|
||
console.log('\n首次启动,已生成访问令牌:\n ' + config.token + '\n (存在 data/config.json,只有你能读)\n')
|
||
}
|
||
index = await json(INDEX, { images: [] })
|
||
if (!Array.isArray(index.images)) index.images = []
|
||
console.log(`图床已启动 http://${HOST}:${PORT} · ${index.images.length} 张图`)
|
||
}
|
||
|
||
// ---------- 工具 ----------
|
||
|
||
const send = (res, status, body, headers = {}) => {
|
||
const payload = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)
|
||
res.writeHead(status, {
|
||
'Content-Type': typeof body === 'string' ? 'text/plain; charset=utf-8' : 'application/json; charset=utf-8',
|
||
'Content-Length': Buffer.byteLength(payload),
|
||
...headers,
|
||
})
|
||
res.end(payload)
|
||
}
|
||
|
||
const apiOk = (res, data) => send(res, 200, data)
|
||
const apiErr = (res, status, message) => send(res, status, { error: message })
|
||
|
||
const safeName = (name) => {
|
||
const base = String(name || 'image').split(/[\\/]/).pop().replace(/[\u0000-\u001f]/g, '').trim()
|
||
return base.slice(0, 120) || 'image'
|
||
}
|
||
|
||
const tokenOf = (req, url) =>
|
||
req.headers['x-token'] || (req.headers.authorization || '').replace(/^Bearer\s+/i, '') || url.searchParams.get('token') || ''
|
||
|
||
const authed = (req, url) => {
|
||
const token = tokenOf(req, url)
|
||
return Boolean(token) && token.length === config.token.length &&
|
||
createHash('sha256').update(token).digest('hex') === createHash('sha256').update(config.token).digest('hex')
|
||
}
|
||
|
||
function publicItem(item) {
|
||
return {
|
||
id: item.id,
|
||
name: item.name,
|
||
ext: item.ext,
|
||
mime: item.mime,
|
||
size: item.size,
|
||
width: item.width ?? null,
|
||
height: item.height ?? null,
|
||
tags: item.tags ?? [],
|
||
note: item.note ?? '',
|
||
createdAt: item.createdAt,
|
||
url: `/i/${item.id}${item.ext}`,
|
||
thumb: item.thumb ? `/t/${item.id}.webp` : `/i/${item.id}${item.ext}`,
|
||
}
|
||
}
|
||
|
||
async function readBody(req, limit = MAX_BYTES) {
|
||
const chunks = []
|
||
let total = 0
|
||
for await (const chunk of req) {
|
||
total += chunk.length
|
||
if (total > limit) throw Object.assign(new Error('文件太大了(上限 25 MB)'), { status: 413 })
|
||
chunks.push(chunk)
|
||
}
|
||
return Buffer.concat(chunks)
|
||
}
|
||
|
||
// 只取 PNG/JPEG/WebP/GIF 的尺寸,够用就停,不解码整张图。
|
||
function imageSize(buffer) {
|
||
try {
|
||
if (buffer.length > 24 && buffer.toString('ascii', 1, 4) === 'PNG') {
|
||
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) }
|
||
}
|
||
if (buffer.length > 4 && buffer[0] === 0xff && buffer[1] === 0xd8) {
|
||
let offset = 2
|
||
while (offset < buffer.length - 9) {
|
||
if (buffer[offset] !== 0xff) { offset += 1; continue }
|
||
const marker = buffer[offset + 1]
|
||
const length = buffer.readUInt16BE(offset + 2)
|
||
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
|
||
return { height: buffer.readUInt16BE(offset + 5), width: buffer.readUInt16BE(offset + 7) }
|
||
}
|
||
offset += 2 + length
|
||
}
|
||
}
|
||
if (buffer.length > 30 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP') {
|
||
const kind = buffer.toString('ascii', 12, 16)
|
||
if (kind === 'VP8X') return { width: 1 + buffer.readUIntLE(24, 3), height: 1 + buffer.readUIntLE(27, 3) }
|
||
if (kind === 'VP8 ') return { width: buffer.readUInt16LE(26) & 0x3fff, height: buffer.readUInt16LE(28) & 0x3fff }
|
||
if (kind === 'VP8L') {
|
||
const bits = buffer.readUInt32LE(21)
|
||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }
|
||
}
|
||
}
|
||
} catch {}
|
||
return {}
|
||
}
|
||
|
||
// ---------- 路由 ----------
|
||
|
||
async function handleApi(req, res, url) {
|
||
const { pathname } = url
|
||
|
||
if (pathname === '/api/ping' && req.method === 'GET') {
|
||
return apiOk(res, { ok: true, auth: authed(req, url), count: index.images.length })
|
||
}
|
||
|
||
if (!authed(req, url)) {
|
||
return apiErr(res, 401, '令牌不对,去 data/config.json 里抄一下。')
|
||
}
|
||
|
||
if (pathname === '/api/upload' && req.method === 'POST') {
|
||
const buffer = await readBody(req)
|
||
if (!buffer.length) return apiErr(res, 400, '没有收到内容。')
|
||
const name = safeName(url.searchParams.get('name'))
|
||
const ext = extname(name).toLowerCase()
|
||
if (!ALLOWED.has(ext)) return apiErr(res, 415, `不支持的格式:${ext || '(没有扩展名)'}`)
|
||
|
||
const sha = createHash('sha256').update(buffer).digest('hex')
|
||
const duplicate = index.images.find((item) => item.sha === sha)
|
||
if (duplicate) return apiOk(res, { item: publicItem(duplicate), duplicate: true })
|
||
|
||
const id = randomBytes(6).toString('hex')
|
||
const now = new Date()
|
||
const dir = join(IMAGES, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, '0'))
|
||
await mkdir(dir, { recursive: true })
|
||
await writeFile(join(dir, id + ext), buffer)
|
||
|
||
const size = imageSize(buffer)
|
||
const item = {
|
||
id,
|
||
name,
|
||
ext,
|
||
mime: MIME[ext],
|
||
size: buffer.length,
|
||
sha,
|
||
...size,
|
||
tags: [],
|
||
note: '',
|
||
createdAt: now.toISOString(),
|
||
file: normalize(join(dir, id + ext)),
|
||
thumb: false,
|
||
}
|
||
index.images.unshift(item)
|
||
await saveIndex()
|
||
return apiOk(res, { item: publicItem(item), duplicate: false })
|
||
}
|
||
|
||
// 客户端生成缩略图后回传(服务端不装 sharp,省得依赖编译)
|
||
const thumbMatch = pathname.match(/^\/api\/thumb\/([a-f0-9]{12})$/)
|
||
if (thumbMatch && req.method === 'POST') {
|
||
const item = index.images.find((entry) => entry.id === thumbMatch[1])
|
||
if (!item) return apiErr(res, 404, '没有这张图。')
|
||
const buffer = await readBody(req, 2 * 1024 * 1024)
|
||
if (!buffer.length) return apiErr(res, 400, '缩略图是空的。')
|
||
await writeFile(join(THUMBS, item.id + '.webp'), buffer)
|
||
item.thumb = true
|
||
await saveIndex()
|
||
return apiOk(res, { item: publicItem(item) })
|
||
}
|
||
|
||
if (pathname === '/api/images' && req.method === 'GET') {
|
||
const q = (url.searchParams.get('q') || '').trim().toLowerCase()
|
||
const tag = (url.searchParams.get('tag') || '').trim()
|
||
const sort = url.searchParams.get('sort') || 'new'
|
||
const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 1000)
|
||
let list = index.images
|
||
if (q) list = list.filter((item) => item.name.toLowerCase().includes(q) || (item.tags || []).some((t) => t.toLowerCase().includes(q)))
|
||
if (tag) list = list.filter((item) => (item.tags || []).includes(tag))
|
||
list = [...list].sort((a, b) => (sort === 'size' ? b.size - a.size : sort === 'old' ? a.createdAt.localeCompare(b.createdAt) : b.createdAt.localeCompare(a.createdAt)))
|
||
const tags = [...new Set(index.images.flatMap((item) => item.tags || []))].sort()
|
||
return apiOk(res, { total: index.images.length, items: list.slice(0, limit).map(publicItem), tags })
|
||
}
|
||
|
||
const idMatch = pathname.match(/^\/api\/images\/([a-f0-9]{12})$/)
|
||
if (idMatch) {
|
||
const item = index.images.find((entry) => entry.id === idMatch[1])
|
||
if (!item) return apiErr(res, 404, '没有这张图。')
|
||
if (req.method === 'PATCH') {
|
||
const body = JSON.parse((await readBody(req, 64 * 1024)).toString() || '{}')
|
||
if (typeof body.name === 'string' && body.name.trim()) {
|
||
const next = safeName(body.name)
|
||
const ext = extname(next).toLowerCase()
|
||
if (ALLOWED.has(ext)) item.ext = ext
|
||
item.name = next
|
||
}
|
||
if (Array.isArray(body.tags)) item.tags = body.tags.map((tag) => String(tag).trim()).filter(Boolean).slice(0, 20)
|
||
if (typeof body.note === 'string') item.note = body.note.slice(0, 500)
|
||
await saveIndex()
|
||
return apiOk(res, { item: publicItem(item) })
|
||
}
|
||
if (req.method === 'DELETE') {
|
||
await unlink(item.file).catch(() => {})
|
||
await unlink(join(THUMBS, item.id + '.webp')).catch(() => {})
|
||
index.images = index.images.filter((entry) => entry.id !== item.id)
|
||
await saveIndex()
|
||
return apiOk(res, { deleted: item.id })
|
||
}
|
||
}
|
||
|
||
if (pathname === '/api/delete' && req.method === 'POST') {
|
||
const body = JSON.parse((await readBody(req, 64 * 1024)).toString() || '{}')
|
||
const ids = new Set((body.ids || []).slice(0, 500))
|
||
const removed = []
|
||
for (const item of index.images.filter((entry) => ids.has(entry.id))) {
|
||
await unlink(item.file).catch(() => {})
|
||
await unlink(join(THUMBS, item.id + '.webp')).catch(() => {})
|
||
removed.push(item.id)
|
||
}
|
||
index.images = index.images.filter((entry) => !ids.has(entry.id))
|
||
await saveIndex()
|
||
return apiOk(res, { removed })
|
||
}
|
||
|
||
if (pathname === '/api/stats' && req.method === 'GET') {
|
||
const bytes = index.images.reduce((sum, item) => sum + item.size, 0)
|
||
const today = new Date().toISOString().slice(0, 10)
|
||
return apiOk(res, {
|
||
count: index.images.length,
|
||
bytes,
|
||
today: index.images.filter((item) => item.createdAt.startsWith(today)).length,
|
||
tags: [...new Set(index.images.flatMap((item) => item.tags || []))].length,
|
||
})
|
||
}
|
||
|
||
return apiErr(res, 404, '没有这个接口。')
|
||
}
|
||
|
||
async function serveFile(req, res, filePath, { cache = 'public, max-age=31536000, immutable' } = {}) {
|
||
try {
|
||
const info = await stat(filePath)
|
||
if (!info.isFile()) throw new Error('not a file')
|
||
res.writeHead(200, {
|
||
'Content-Type': MIME[extname(filePath).toLowerCase()] || 'application/octet-stream',
|
||
'Content-Length': info.size,
|
||
'Cache-Control': cache,
|
||
})
|
||
return createReadStream(filePath).pipe(res)
|
||
} catch {
|
||
return send(res, 404, '找不到这个文件。')
|
||
}
|
||
}
|
||
|
||
const CONTENT_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json' }
|
||
|
||
async function handleStatic(req, res, url) {
|
||
let pathname = decodeURIComponent(url.pathname)
|
||
if (pathname === '/' || pathname === '') pathname = '/index.html'
|
||
const target = resolve(PUBLIC, '.' + normalize(pathname))
|
||
if (!target.startsWith(PUBLIC + sep) && target !== PUBLIC) return send(res, 403, '不允许访问。')
|
||
try {
|
||
const info = await stat(target)
|
||
if (!info.isFile()) return send(res, 404, '没有这个页面。')
|
||
res.writeHead(200, {
|
||
'Content-Type': CONTENT_TYPES[extname(target).toLowerCase()] || 'application/octet-stream',
|
||
'Content-Length': info.size,
|
||
'Cache-Control': 'no-cache',
|
||
})
|
||
return createReadStream(target).pipe(res)
|
||
} catch {
|
||
return send(res, 404, '没有这个页面。')
|
||
}
|
||
}
|
||
|
||
const server = createServer(async (req, res) => {
|
||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`)
|
||
try {
|
||
if (url.pathname.startsWith('/api/')) return await handleApi(req, res, url)
|
||
|
||
const imageMatch = url.pathname.match(/^\/i\/([a-f0-9]{12})(\.[a-z0-9]+)?$/)
|
||
if (imageMatch) {
|
||
const item = index.images.find((entry) => entry.id === imageMatch[1])
|
||
if (!item) return send(res, 404, '没有这张图。')
|
||
return serveFile(req, res, item.file)
|
||
}
|
||
|
||
const thumbMatch = url.pathname.match(/^\/t\/([a-f0-9]{12})\.webp$/)
|
||
if (thumbMatch) {
|
||
const item = index.images.find((entry) => entry.id === thumbMatch[1])
|
||
if (!item) return send(res, 404, '没有这张图。')
|
||
const thumb = join(THUMBS, item.id + '.webp')
|
||
if (item.thumb) return serveFile(req, res, thumb)
|
||
if (item.ext === '.svg') return serveFile(req, res, item.file, { cache: 'no-cache' })
|
||
return serveFile(req, res, item.file, { cache: 'no-cache' })
|
||
}
|
||
|
||
return await handleStatic(req, res, url)
|
||
} catch (error) {
|
||
const status = error.status || 500
|
||
if (status >= 500) console.error('[error]', error)
|
||
return apiErr(res, status, error.message || '服务器出错了。')
|
||
}
|
||
})
|
||
|
||
server.listen(PORT, HOST, () => boot().catch((error) => {
|
||
console.error('启动失败:', error)
|
||
process.exit(1)
|
||
}))
|