665 lines
29 KiB
JavaScript
665 lines
29 KiB
JavaScript
// 图床:多用户版。账号、会话、图片信息都在 data/imgbed.db(SQLite),图片文件在 data/images/。
|
||
import { createServer } from 'node:http'
|
||
import { createHash } from 'node:crypto'
|
||
import { mkdir, readFile, writeFile, stat, unlink } from 'node:fs/promises'
|
||
import { createReadStream } from 'node:fs'
|
||
import { extname, join, normalize, resolve, sep } from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
import {
|
||
openDb, getUser, getUserByUsername, getUserByApiKeyHash, countUsers, createUser,
|
||
publicUser, userUsage, listUsers, publicImage, migrateLegacy,
|
||
setUserEmail, getUserByEmail, createReset, getReset, dropReset, dropResets, setUserSmtp,
|
||
} from './lib/db.mjs'
|
||
import { loadMailConfig, sendMail } from './lib/mail.mjs'
|
||
import { encrypt, decrypt, maskSecret } from './lib/secret.mjs'
|
||
import {
|
||
hashPassword, verifyPassword, createSession, sessionUser, destroySession,
|
||
parseCookies, cookieHeader, clearCookie, newApiKey, hashApiKey,
|
||
tooManyAttempts, noteAttempt, resetAttempts, randomId,
|
||
} from './lib/auth.mjs'
|
||
|
||
const ROOT = fileURLToPath(new URL('.', import.meta.url))
|
||
const DATA = process.env.IMGBED_DATA || join(ROOT, 'data')
|
||
const IMAGES = join(DATA, 'images')
|
||
const THUMBS = join(DATA, 'thumbs')
|
||
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 DEFAULT_QUOTA = 512 * 1024 * 1024
|
||
const COOKIE = 'imgbed_session'
|
||
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))
|
||
|
||
const db = openDb(DATA)
|
||
const MAIL = loadMailConfig(DATA)
|
||
const PUBLIC_URL = (process.env.IMGBED_URL || 'http://110.42.217.133:8088').replace(/\/+$/, '')
|
||
const RESET_MINUTES = 30
|
||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||
const resetToken = () => randomId(32)
|
||
|
||
// 常见邮箱的 SMTP 默认值
|
||
const SMTP_PRESETS = {
|
||
'qq.com': { host: 'smtp.qq.com', port: 587, secure: 'starttls' },
|
||
'foxmail.com': { host: 'smtp.qq.com', port: 587, secure: 'starttls' },
|
||
'163.com': { host: 'smtp.163.com', port: 465, secure: 'ssl' },
|
||
'126.com': { host: 'smtp.126.com', port: 465, secure: 'ssl' },
|
||
'gmail.com': { host: 'smtp.gmail.com', port: 587, secure: 'starttls' },
|
||
'outlook.com': { host: 'smtp-mail.outlook.com', port: 587, secure: 'starttls' },
|
||
'hotmail.com': { host: 'smtp-mail.outlook.com', port: 587, secure: 'starttls' },
|
||
'aliyun.com': { host: 'smtp.aliyun.com', port: 465, secure: 'ssl' },
|
||
}
|
||
|
||
function smtpFor(user) {
|
||
const domain = (user.email || '').split('@')[1] || ''
|
||
const preset = SMTP_PRESETS[domain] || { host: domain ? `smtp.${domain}` : '', port: 587, secure: 'starttls' }
|
||
return {
|
||
host: user.smtp_host || preset.host,
|
||
port: Number(user.smtp_port || preset.port),
|
||
secure: user.smtp_secure || preset.secure,
|
||
}
|
||
}
|
||
|
||
// 某个用户自己的发信配置(没有就返回 null)
|
||
function userMailConfig(user) {
|
||
if (!user?.email) return null
|
||
const pass = decrypt(DATA, user.smtp_pass)
|
||
if (!pass) return null
|
||
const conf = smtpFor(user)
|
||
if (!conf.host) return null
|
||
return {
|
||
smtpHost: conf.host,
|
||
smtpPort: conf.port,
|
||
smtpSecure: conf.secure,
|
||
smtpUser: user.email,
|
||
smtpPass: pass,
|
||
mailFrom: user.email,
|
||
fromName: user.display_name || 'imgbed',
|
||
}
|
||
}
|
||
|
||
function describeMail(user) {
|
||
const conf = userMailConfig(user)
|
||
if (!conf) return { configured: false, email: user?.email || '', host: '', hint: '' }
|
||
return {
|
||
configured: true,
|
||
email: user.email,
|
||
host: `${conf.smtpHost}:${conf.smtpPort}`,
|
||
secure: conf.smtpSecure,
|
||
passHint: maskSecret(decrypt(DATA, user.smtp_pass)),
|
||
}
|
||
}
|
||
const hashToken = (t) => createHash('sha256').update(t).digest('hex')
|
||
|
||
// ---------- 基础工具 ----------
|
||
|
||
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'
|
||
}
|
||
|
||
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)
|
||
}
|
||
|
||
const readJson = async (req, limit = 64 * 1024) => {
|
||
const text = (await readBody(req, limit)).toString() || '{}'
|
||
try {
|
||
return JSON.parse(text)
|
||
} catch {
|
||
throw Object.assign(new Error('请求格式不对'), { status: 400 })
|
||
}
|
||
}
|
||
|
||
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 {}
|
||
}
|
||
|
||
// ---------- 身份 ----------
|
||
|
||
const clientIp = (req) => (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket.remoteAddress || ''
|
||
|
||
function currentUser(req) {
|
||
const cookies = parseCookies(req.headers.cookie)
|
||
const sessionId = cookies[COOKIE]
|
||
const viaSession = sessionUser(db, sessionId)
|
||
if (viaSession) return { user: viaSession, sid: sessionId }
|
||
|
||
const key = req.headers['x-api-key'] || (req.headers.authorization || '').replace(/^Bearer\s+/i, '')
|
||
if (key) {
|
||
const user = getUserByApiKeyHash(db, hashApiKey(String(key)))
|
||
if (user && !user.disabled) return { user, sid: null }
|
||
}
|
||
return { user: null, sid: sessionId || null }
|
||
}
|
||
|
||
const isAdmin = (user) => user?.role === 'admin'
|
||
|
||
function cookieFor(res, sessionId, req) {
|
||
const secure = (req.headers['x-forwarded-proto'] || '').includes('https')
|
||
res.setHeader('Set-Cookie', cookieHeader(COOKIE, sessionId, { secure }))
|
||
}
|
||
|
||
// ---------- 路由 ----------
|
||
|
||
async function handleApi(req, res, url) {
|
||
const { pathname } = url
|
||
const { user, sid } = currentUser(req)
|
||
|
||
// 公开:健康检查 / 注册 / 登录
|
||
if (pathname === '/api/health') {
|
||
return apiOk(res, {
|
||
ok: true,
|
||
hasUsers: countUsers(db) > 0,
|
||
user: user ? publicUser(user) : null,
|
||
})
|
||
}
|
||
|
||
if (pathname === '/api/register' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const username = String(body.username || '').trim()
|
||
const password = String(body.password || '')
|
||
const displayName = String(body.displayName || '').trim()
|
||
const email = String(body.email || '').trim()
|
||
if (!/^[A-Za-z0-9_\u4e00-\u9fa5-]{2,20}$/.test(username)) {
|
||
return apiErr(res, 400, '用户名 2–20 个字,只能是字母、数字、下划线、横线或中文。')
|
||
}
|
||
if (password.length < 6) return apiErr(res, 400, '密码至少 6 位。')
|
||
if (email && !EMAIL_RE.test(email)) return apiErr(res, 400, '邮箱格式看着不太对。')
|
||
if (getUserByUsername(db, username)) return apiErr(res, 409, '这个用户名已经有人用了。')
|
||
|
||
const { salt, hash } = hashPassword(password)
|
||
const first = countUsers(db) === 0
|
||
const created = createUser(db, {
|
||
username, displayName, passHash: hash, passSalt: salt,
|
||
role: first ? 'admin' : 'user', quotaBytes: DEFAULT_QUOTA, email,
|
||
})
|
||
const sessionId = createSession(db, created.id, req.headers['user-agent'])
|
||
cookieFor(res, sessionId, req)
|
||
return apiOk(res, { user: publicUser(created), usage: userUsage(db, created.id), first: first })
|
||
}
|
||
|
||
// 忘记密码:发一封带重置链接的邮件
|
||
if (pathname === '/api/forgot' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const account = String(body.account || '').trim()
|
||
if (!account) return apiErr(res, 400, '填用户名或邮箱。')
|
||
const byName = getUserByUsername(db, account)
|
||
const byMail = byName ? undefined : getUserByEmail(db, account)
|
||
const target = byName || byMail
|
||
const ip = clientIp(req)
|
||
const mail = userMailConfig(target) || MAIL
|
||
if (!mail) return apiErr(res, 503, '服务器还没配发信邮箱。登录后在「设置 → 邮箱与发信」里填邮箱和 SMTP 授权码,就能自己找回。')
|
||
if (!target || target.disabled || !target.email) {
|
||
// 不暴露账号是否存在
|
||
return apiOk(res, { ok: true, sent: false })
|
||
}
|
||
const token = resetToken()
|
||
createReset(db, {
|
||
tokenHash: hashToken(token),
|
||
userId: target.id,
|
||
expiresAt: new Date(Date.now() + RESET_MINUTES * 60000).toISOString(),
|
||
ip,
|
||
})
|
||
const link = `${PUBLIC_URL}/#/reset?token=${token}`
|
||
const text = [
|
||
`你好,${target.display_name || target.username}:`,
|
||
'',
|
||
`有人在 ${new Date().toLocaleString('zh-CN')} 申请重置 imgbed 的登录密码。`,
|
||
`点这个链接设置新密码(${RESET_MINUTES} 分钟内有效,只能用一次):`,
|
||
'',
|
||
link,
|
||
'',
|
||
'如果链接过期,重新在登录页点「忘记密码」再发一封。',
|
||
'不是你操作的,忽略这封邮件即可,密码不会变。',
|
||
'',
|
||
'—— imgbed',
|
||
].join('\n')
|
||
try {
|
||
await sendMail(mail, { to: target.email, subject: `重置 imgbed 密码(${RESET_MINUTES} 分钟内有效)`, text })
|
||
} catch (err) {
|
||
console.error('[mail]', err.message)
|
||
return apiErr(res, 502, `邮件没发出去:${err.message.slice(0, 120)}`)
|
||
}
|
||
return apiOk(res, { ok: true, sent: true })
|
||
}
|
||
|
||
if (pathname === '/api/reset/verify' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const row = getReset(db, hashToken(String(body.token || '')))
|
||
if (!row) return apiOk(res, { valid: false, reason: '链接无效或已经用过了。' })
|
||
if (new Date(row.expires_at) < new Date()) return apiOk(res, { valid: false, reason: '链接过期了,重新发一封。' })
|
||
const owner = getUser(db, row.user_id)
|
||
return apiOk(res, { valid: true, username: owner?.username || '', displayName: owner?.display_name || '' })
|
||
}
|
||
|
||
if (pathname === '/api/reset' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const token = String(body.token || '')
|
||
const password = String(body.password || '')
|
||
if (password.length < 6) return apiErr(res, 400, '新密码至少 6 位。')
|
||
const row = getReset(db, hashToken(token))
|
||
if (!row) return apiErr(res, 400, '链接无效或已经用过了。')
|
||
if (new Date(row.expires_at) < new Date()) {
|
||
dropReset(db, row.token_hash)
|
||
return apiErr(res, 400, '链接过期了,重新发一封。')
|
||
}
|
||
const { salt, hash } = hashPassword(password)
|
||
db.prepare('UPDATE users SET pass_hash = ?, pass_salt = ? WHERE id = ?').run(hash, salt, row.user_id)
|
||
db.prepare('DELETE FROM sessions WHERE user_id = ?').run(row.user_id)
|
||
dropResets(db, row.user_id)
|
||
resetAttempts(clientIp(req), '')
|
||
return apiOk(res, { ok: true })
|
||
}
|
||
|
||
if (pathname === '/api/login' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const username = String(body.username || '').trim()
|
||
const password = String(body.password || '')
|
||
const ip = clientIp(req)
|
||
if (tooManyAttempts(ip, username)) return apiErr(res, 429, '试太多次了,过几分钟再来。')
|
||
const found = getUserByUsername(db, username)
|
||
if (!found || !verifyPassword(password, found.pass_salt, found.pass_hash)) {
|
||
noteAttempt(ip, username)
|
||
return apiErr(res, 401, '用户名或密码不对。')
|
||
}
|
||
if (found.disabled) return apiErr(res, 403, '这个账号已被管理员停用。')
|
||
resetAttempts(ip, username)
|
||
const sessionId = createSession(db, found.id, req.headers['user-agent'])
|
||
cookieFor(res, sessionId, req)
|
||
return apiOk(res, { user: publicUser(found), usage: userUsage(db, found.id) })
|
||
}
|
||
|
||
if (pathname === '/api/logout' && req.method === 'POST') {
|
||
destroySession(db, sid)
|
||
res.setHeader('Set-Cookie', clearCookie(COOKIE))
|
||
return apiOk(res, { ok: true })
|
||
}
|
||
|
||
if (!user) {
|
||
const sentKey = req.headers['x-api-key'] || /^Bearer\s+/i.test(req.headers.authorization || '')
|
||
return apiErr(res, 401, sentKey ? 'API 密钥无效或已被撤销,去「设置」里重新生成一个。' : '先登录。')
|
||
}
|
||
|
||
if (pathname === '/api/me' && req.method === 'GET') {
|
||
return apiOk(res, {
|
||
user: publicUser(user, { mail: describeMail(user) }),
|
||
usage: userUsage(db, user.id),
|
||
admin: isAdmin(user),
|
||
})
|
||
}
|
||
|
||
if (pathname === '/api/password' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
if (!verifyPassword(String(body.current || ''), user.pass_salt, user.pass_hash)) {
|
||
return apiErr(res, 403, '当前密码不对。')
|
||
}
|
||
const next = String(body.next || '')
|
||
if (next.length < 6) return apiErr(res, 400, '新密码至少 6 位。')
|
||
const { salt, hash } = hashPassword(next)
|
||
db.prepare('UPDATE users SET pass_hash = ?, pass_salt = ? WHERE id = ?').run(hash, salt, user.id)
|
||
db.prepare('DELETE FROM sessions WHERE user_id = ? AND id <> ?').run(user.id, sid || '')
|
||
return apiOk(res, { ok: true })
|
||
}
|
||
|
||
if (pathname === '/api/mail/test' && req.method === 'POST') {
|
||
const fresh = getUser(db, user.id)
|
||
const conf = userMailConfig(fresh)
|
||
if (!conf) return apiErr(res, 400, '还没配好:先填邮箱,再填 SMTP 授权码。')
|
||
try {
|
||
await sendMail(conf, {
|
||
to: fresh.email,
|
||
subject: 'imgbed 测试邮件',
|
||
text: `这封是测试邮件。收到说明 ${fresh.email} 的发信配置能用,忘记密码时就能收到重置链接了。`,
|
||
})
|
||
return apiOk(res, { ok: true, to: fresh.email })
|
||
} catch (err) {
|
||
return apiErr(res, 502, `发不出去:${err.message.slice(0, 140)}`)
|
||
}
|
||
}
|
||
|
||
if (pathname === '/api/apikey' && req.method === 'POST') {
|
||
const { key, hash, hint } = newApiKey()
|
||
db.prepare('UPDATE users SET api_key_hash = ?, api_key_hint = ? WHERE id = ?').run(hash, hint, user.id)
|
||
return apiOk(res, { key, hint })
|
||
}
|
||
|
||
if (pathname === '/api/apikey' && req.method === 'DELETE') {
|
||
db.prepare('UPDATE users SET api_key_hash = NULL, api_key_hint = NULL WHERE id = ?').run(user.id)
|
||
return apiOk(res, { ok: true })
|
||
}
|
||
|
||
if (pathname === '/api/profile' && req.method === 'PATCH') {
|
||
const body = await readJson(req)
|
||
const name = String(body.displayName || '').trim().slice(0, 40)
|
||
if (name) db.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(name, user.id)
|
||
if (body.email !== undefined) {
|
||
const email = String(body.email || '').trim()
|
||
if (email && !EMAIL_RE.test(email)) return apiErr(res, 400, '邮箱格式看着不太对。')
|
||
setUserEmail(db, user.id, email)
|
||
}
|
||
if (body.smtpHost !== undefined || body.smtpPass !== undefined || body.smtpPort !== undefined) {
|
||
const fresh = getUser(db, user.id)
|
||
const host = body.smtpHost !== undefined ? String(body.smtpHost || '').trim().slice(0, 120) : fresh.smtp_host || ''
|
||
const port = body.smtpPort !== undefined ? Number(body.smtpPort) || 0 : fresh.smtp_port || 0
|
||
const secure = body.smtpSecure !== undefined ? String(body.smtpSecure || '') : fresh.smtp_secure || ''
|
||
let pass = fresh.smtp_pass
|
||
if (body.clearSmtpPass) pass = null
|
||
else if (typeof body.smtpPass === 'string' && body.smtpPass.trim()) pass = encrypt(DATA, body.smtpPass.trim())
|
||
if ((host || pass) && !(getUser(db, user.id).email || '')) {
|
||
return apiErr(res, 400, '先填邮箱,再配 SMTP。')
|
||
}
|
||
setUserSmtp(db, user.id, { host, port, secure, pass })
|
||
}
|
||
return apiOk(res, { user: publicUser(getUser(db, user.id), { mail: describeMail(getUser(db, user.id)) }) })
|
||
}
|
||
|
||
// 上传
|
||
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 usage = userUsage(db, user.id)
|
||
if (usage.bytes + buffer.length > user.quota_bytes) {
|
||
return apiErr(res, 413, `空间不够了:已用 ${(usage.bytes / 1048576).toFixed(0)} MB,上限 ${(user.quota_bytes / 1048576).toFixed(0)} MB。`)
|
||
}
|
||
|
||
const sha = createHash('sha256').update(buffer).digest('hex')
|
||
const duplicate = db.prepare('SELECT * FROM images WHERE user_id = ? AND sha = ?').get(user.id, sha)
|
||
if (duplicate) return apiOk(res, { item: publicImage(duplicate), duplicate: true })
|
||
|
||
const id = randomId(6)
|
||
const now = new Date()
|
||
const dir = join(IMAGES, `u${user.id}`, 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)
|
||
db.prepare(
|
||
'INSERT INTO images (id, user_id, name, ext, mime, size, sha, width, height, tags, note, public, path, thumb, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, 0, ?)'
|
||
).run(id, user.id, name, ext, MIME[ext], buffer.length, sha, size.width ?? null, size.height ?? null, '[]', '', join(dir, id + ext), now.toISOString())
|
||
|
||
return apiOk(res, { item: publicImage(db.prepare('SELECT * FROM images WHERE id = ?').get(id)), duplicate: false })
|
||
}
|
||
|
||
const ownImage = (id) => db.prepare('SELECT * FROM images WHERE id = ?').get(id)
|
||
|
||
const thumbMatch = pathname.match(/^\/api\/thumb\/([a-f0-9]{12})$/)
|
||
if (thumbMatch && req.method === 'POST') {
|
||
const item = ownImage(thumbMatch[1])
|
||
if (!item || (item.user_id !== user.id && !isAdmin(user))) return apiErr(res, 404, '没有这张图。')
|
||
const buffer = await readBody(req, 2 * 1024 * 1024)
|
||
if (!buffer.length) return apiErr(res, 400, '缩略图是空的。')
|
||
await mkdir(THUMBS, { recursive: true })
|
||
await writeFile(join(THUMBS, item.id + '.webp'), buffer)
|
||
db.prepare('UPDATE images SET thumb = 1 WHERE id = ?').run(item.id)
|
||
return apiOk(res, { item: publicImage(ownImage(item.id)) })
|
||
}
|
||
|
||
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 scope = url.searchParams.get('scope') || 'mine'
|
||
const owner = isAdmin(user) && scope === 'all' ? null : user.id
|
||
const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 1000)
|
||
|
||
let rows = db.prepare('SELECT * FROM images WHERE (? IS NULL OR user_id = ?)').all(owner, owner)
|
||
if (q) rows = rows.filter((row) => row.name.toLowerCase().includes(q) || row.tags.toLowerCase().includes(q))
|
||
if (tag) rows = rows.filter((row) => JSON.parse(row.tags || '[]').includes(tag))
|
||
rows.sort((a, b) => (sort === 'size' ? b.size - a.size : sort === 'old' ? a.created_at.localeCompare(b.created_at) : b.created_at.localeCompare(a.created_at)))
|
||
const tags = [...new Set(rows.flatMap((row) => JSON.parse(row.tags || '[]')))].sort()
|
||
return apiOk(res, { total: rows.length, items: rows.slice(0, limit).map(publicImage), tags })
|
||
}
|
||
|
||
const imageMatch = pathname.match(/^\/api\/images\/([a-f0-9]{12})$/)
|
||
if (imageMatch) {
|
||
const item = ownImage(imageMatch[1])
|
||
if (!item || (item.user_id !== user.id && !isAdmin(user))) return apiErr(res, 404, '没有这张图。')
|
||
if (req.method === 'PATCH') {
|
||
const body = await readJson(req)
|
||
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 = JSON.stringify(body.tags.map((tag) => String(tag).trim()).filter(Boolean).slice(0, 20))
|
||
if (typeof body.note === 'string') item.note = body.note.slice(0, 500)
|
||
if (typeof body.public === 'boolean') item.public = body.public ? 1 : 0
|
||
db.prepare('UPDATE images SET name = ?, ext = ?, tags = ?, note = ?, public = ? WHERE id = ?')
|
||
.run(item.name, item.ext, item.tags, item.note, item.public, item.id)
|
||
return apiOk(res, { item: publicImage(ownImage(item.id)) })
|
||
}
|
||
if (req.method === 'DELETE') {
|
||
await unlink(item.path).catch(() => {})
|
||
await unlink(join(THUMBS, item.id + '.webp')).catch(() => {})
|
||
db.prepare('DELETE FROM images WHERE id = ?').run(item.id)
|
||
return apiOk(res, { deleted: item.id })
|
||
}
|
||
}
|
||
|
||
if (pathname === '/api/delete' && req.method === 'POST') {
|
||
const body = await readJson(req)
|
||
const ids = (body.ids || []).slice(0, 500)
|
||
const removed = []
|
||
for (const id of ids) {
|
||
const item = ownImage(id)
|
||
if (!item || (item.user_id !== user.id && !isAdmin(user))) continue
|
||
await unlink(item.path).catch(() => {})
|
||
await unlink(join(THUMBS, item.id + '.webp')).catch(() => {})
|
||
db.prepare('DELETE FROM images WHERE id = ?').run(item.id)
|
||
removed.push(item.id)
|
||
}
|
||
return apiOk(res, { removed })
|
||
}
|
||
|
||
if (pathname === '/api/stats' && req.method === 'GET') {
|
||
const usage = userUsage(db, user.id)
|
||
const today = new Date().toISOString().slice(0, 10)
|
||
const todayCount = db.prepare("SELECT COUNT(*) AS n FROM images WHERE user_id = ? AND created_at LIKE ?").get(user.id, `${today}%`).n
|
||
return apiOk(res, {
|
||
count: usage.count,
|
||
bytes: usage.bytes,
|
||
today: todayCount,
|
||
quotaBytes: user.quota_bytes,
|
||
tags: db.prepare('SELECT tags FROM images WHERE user_id = ?').all(user.id).flatMap((row) => JSON.parse(row.tags || '[]')).filter((tag, index, all) => all.indexOf(tag) === index).length,
|
||
})
|
||
}
|
||
|
||
// ---- 管理员 ----
|
||
if (pathname === '/api/users' && req.method === 'GET') {
|
||
if (!isAdmin(user)) return apiErr(res, 403, '只有管理员能看。')
|
||
const users = listUsers(db).map((row) => publicUser(row, { imageCount: row.image_count, usedBytes: row.used_bytes }))
|
||
return apiOk(res, { users })
|
||
}
|
||
|
||
const userMatch = pathname.match(/^\/api\/users\/(\d+)$/)
|
||
if (userMatch) {
|
||
if (!isAdmin(user)) return apiErr(res, 403, '只有管理员能改。')
|
||
const target = getUser(db, Number(userMatch[1]))
|
||
if (!target) return apiErr(res, 404, '没有这个用户。')
|
||
if (req.method === 'PATCH') {
|
||
const body = await readJson(req)
|
||
const patch = []
|
||
const values = []
|
||
if (typeof body.disabled === 'boolean') {
|
||
if (target.id === user.id && body.disabled) return apiErr(res, 400, '不能停用自己。')
|
||
patch.push('disabled = ?'); values.push(body.disabled ? 1 : 0)
|
||
}
|
||
if (body.quotaBytes !== undefined) {
|
||
const quota = Math.max(10 * 1024 * 1024, Math.min(Number(body.quotaBytes) || 0, 200 * 1024 * 1024 * 1024))
|
||
patch.push('quota_bytes = ?'); values.push(quota)
|
||
}
|
||
if (body.role === 'admin' || body.role === 'user') {
|
||
if (target.id === user.id && body.role !== 'admin') return apiErr(res, 400, '不能取消自己的管理员权限。')
|
||
patch.push('role = ?'); values.push(body.role)
|
||
}
|
||
if (!patch.length) return apiErr(res, 400, '没有要改的内容。')
|
||
db.prepare(`UPDATE users SET ${patch.join(', ')} WHERE id = ?`).run(...values, target.id)
|
||
if (body.disabled) db.prepare('DELETE FROM sessions WHERE user_id = ?').run(target.id)
|
||
const fresh = listUsers(db).find((row) => row.id === target.id)
|
||
return apiOk(res, { user: publicUser(fresh, { imageCount: fresh.image_count, usedBytes: fresh.used_bytes }) })
|
||
}
|
||
if (req.method === 'DELETE') {
|
||
if (target.id === user.id) return apiErr(res, 400, '不能删除自己。')
|
||
const images = db.prepare('SELECT * FROM images WHERE user_id = ?').all(target.id)
|
||
for (const item of images) {
|
||
await unlink(item.path).catch(() => {})
|
||
await unlink(join(THUMBS, item.id + '.webp')).catch(() => {})
|
||
}
|
||
db.prepare('DELETE FROM users WHERE id = ?').run(target.id)
|
||
return apiOk(res, { deleted: target.id, images: images.length })
|
||
}
|
||
}
|
||
|
||
return apiErr(res, 404, '没有这个接口。')
|
||
}
|
||
|
||
async function serveFile(req, res, filePath, { cache = 'private, 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 = db.prepare('SELECT * FROM images WHERE id = ?').get(imageMatch[1])
|
||
if (!item) return send(res, 404, '没有这张图。')
|
||
if (!item.public) {
|
||
const { user } = currentUser(req)
|
||
if (!user || (user.id !== item.user_id && !isAdmin(user))) return send(res, 403, '这张图是私有的,登录主人账号才能看。')
|
||
}
|
||
return serveFile(req, res, item.path, { cache: item.public ? 'public, max-age=31536000, immutable' : 'private, max-age=0, must-revalidate' })
|
||
}
|
||
|
||
const thumbMatch = url.pathname.match(/^\/t\/([a-f0-9]{12})\.webp$/)
|
||
if (thumbMatch) {
|
||
const item = db.prepare('SELECT * FROM images WHERE id = ?').get(thumbMatch[1])
|
||
if (!item) return send(res, 404, '没有这张图。')
|
||
if (!item.public) {
|
||
const { user } = currentUser(req)
|
||
if (!user || (user.id !== item.user_id && !isAdmin(user))) return send(res, 403, '这张图是私有的。')
|
||
}
|
||
const thumb = join(THUMBS, item.id + '.webp')
|
||
return serveFile(req, res, item.thumb ? thumb : item.path, { cache: 'private, max-age=0, must-revalidate' })
|
||
}
|
||
|
||
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, async () => {
|
||
await mkdir(IMAGES, { recursive: true })
|
||
await mkdir(THUMBS, { recursive: true })
|
||
const migrated = migrateLegacy({
|
||
db,
|
||
dataDir: DATA,
|
||
createAdmin: () => {
|
||
const password = randomId(4)
|
||
const { salt, hash } = hashPassword(password)
|
||
const user = createUser(db, { username: 'admin', displayName: '管理员', passHash: hash, passSalt: salt, role: 'admin', quotaBytes: DEFAULT_QUOTA })
|
||
return { user, password }
|
||
},
|
||
})
|
||
if (migrated) {
|
||
console.log(`\n把旧版 index.json 里的 ${migrated.imported} 张图并到了账号 ${migrated.username}`)
|
||
if (migrated.password) console.log(` 账号 admin 的初始密码:${migrated.password}(登录后请改掉)\n`)
|
||
}
|
||
console.log(`图床已启动 http://${HOST}:${PORT} · 账号 ${countUsers(db)} 个`)
|
||
if (countUsers(db) === 0) console.log('还没有账号,打开网页注册的第一个账号就是管理员。\n')
|
||
})
|