加账号系统:登录注册、每人 100 分、用一次扣 1 分、CDK 兑换、管理员后台(SQLite)

由 dsh-go 自动上传 · 2026/11/18 01:56:17
This commit is contained in:
dsh-go committed 2026-11-18 01:56:17 +08:00
1 parent e028c5f70b
commit 36e64bdf2f
16 files changed
+1358 -41

No files matched your search

+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env node
// DevBox 服务端:静态文件 + 账号/积分/CDK/后台 API。零依赖,Node >= 22.5(内置 node:sqlite)。
import { createServer } from 'node:http'
import { readFile, stat } from 'node:fs/promises'
import { extname, join, normalize, resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { homedir } from 'node:os'
import { randomUUID } from 'node:crypto'
import { openDb, publicUser, countUsers, getUserByUsername, getUser, createUser, listUsers, addCredits, consume, createCode, redeemCode, listCodes, codeStats, recentUses, COST_PER_USE, START_CREDITS } from './lib/db.mjs'
import { hashPassword, verifyPassword, createSession, sessionUser, destroySession, destroyUserSessions, parseCookies, cookieHeader, clearCookieHeader, newCode, tooManyAttempts, noteAttempt, resetAttempts, cleanExpired, SESSION_COOKIE } from './lib/auth.mjs'
const ROOT = dirname(fileURLToPath(import.meta.url))
const PORT = Number(process.env.PORT || 8090)
const HOST = process.env.HOST || '0.0.0.0'
const DATA_DIR = process.env.DEVBOX_DATA || join(ROOT, 'data')
const db = openDb(DATA_DIR)
cleanExpired(db)
setInterval(() => cleanExpired(db), 60 * 60 * 1000).unref()
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
'.webmanifest': 'application/manifest+json'
}
const STATIC_ALLOW = [
/^index\.html$/,
/^favicon\.(ico|svg|png)$/,
/^app\.webmanifest$/,
/^css\/[\w.-]+\.css$/,
/^js\/[\w.-]+\.js$/,
/^preview\/[\w.-]+\.(png|jpg|jpeg|webp)$/
]
const USERNAME_RE = /^[A-Za-z0-9_\u4e00-\u9fa5-]{3,20}$/
function json(res, status, body, extraHeaders = {}) {
const text = JSON.stringify(body)
res.writeHead(status, {
'content-type': 'application/json; charset=utf-8',
'cache-control': 'no-store',
'x-content-type-options': 'nosniff',
...extraHeaders
})
res.end(text)
}
async function readJson(req, limit = 64 * 1024) {
const chunks = []
let size = 0
for await (const chunk of req) {
size += chunk.length
if (size > limit) throw new Error('请求体太大')
chunks.push(chunk)
}
if (!chunks.length) return {}
try {
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
} catch {
throw new Error('请求体不是合法 JSON')
}
}
function clientIp(req) {
return String(req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket.remoteAddress || 'local'
}
function sameOrigin(req) {
const origin = req.headers.origin
if (!origin) return true
try {
const host = req.headers.host || ''
return new URL(origin).host === host
} catch {
return false
}
}
function currentUser(req) {
const cookies = parseCookies(req.headers.cookie)
return sessionUser(db, cookies[SESSION_COOKIE])
}
function userView(sessionId, row) {
const u = publicUser(row)
return { ...u, admin: u.role === 'admin' }
}
async function serveStatic(req, res, pathname) {
let rel = decodeURIComponent(pathname).replace(/^\/+/, '')
if (!rel) rel = 'index.html'
if (rel.endsWith('/')) rel += 'index.html'
rel = normalize(rel).replace(/^\.\.(\/|\\|$)/, '')
if (!STATIC_ALLOW.some((re) => re.test(rel))) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
return res.end('404')
}
const file = resolve(ROOT, rel)
if (!file.startsWith(ROOT)) {
res.writeHead(404).end()
return
}
try {
const info = await stat(file)
if (!info.isFile()) throw new Error('not a file')
const body = await readFile(file)
const etag = `"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`
if (req.headers['if-none-match'] === etag) {
res.writeHead(304, { etag })
return res.end()
}
res.writeHead(200, {
'content-type': MIME[extname(file).toLowerCase()] || 'application/octet-stream',
'cache-control': rel.endsWith('.html') ? 'no-cache' : 'public, max-age=3600',
etag,
'x-content-type-options': 'nosniff'
})
res.end(body)
} catch {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
res.end('404')
}
}
async function handleApi(req, res, pathname) {
const method = req.method || 'GET'
if (method !== 'GET' && !sameOrigin(req)) {
return json(res, 403, { ok: false, error: '跨站请求被拒绝' })
}
if (pathname === '/api/health') {
return json(res, 200, { ok: true, hasUsers: countUsers(db) > 0, cost: COST_PER_USE, start: START_CREDITS })
}
if (pathname === '/api/register' && method === 'POST') {
const body = await readJson(req)
const username = String(body.username || '').trim()
const password = String(body.password || '')
if (!USERNAME_RE.test(username)) return json(res, 400, { ok: false, error: '用户名 3–20 位,只能字母、数字、下划线、中划线、汉字' })
if (password.length < 6) return json(res, 400, { ok: false, error: '密码至少 6 位' })
if (getUserByUsername(db, username)) return json(res, 409, { ok: false, error: '这个用户名已经被注册了' })
const first = countUsers(db) === 0
const { salt, hash } = hashPassword(password)
const row = createUser(db, { username, passHash: hash, passSalt: salt, role: first ? 'admin' : 'user' })
const sid = createSession(db, row.id)
return json(res, 200, { ok: true, user: userView(sid, getUser(db, row.id)), first }, { 'set-cookie': cookieHeader(sid, 30 * 24 * 3600) })
}
if (pathname === '/api/login' && method === 'POST') {
const body = await readJson(req)
const username = String(body.username || '').trim()
const password = String(body.password || '')
const key = `${clientIp(req)}|${username.toLowerCase()}`
if (tooManyAttempts(key)) return json(res, 429, { ok: false, error: '试太多次了,等 5 分钟再试' })
const row = getUserByUsername(db, username)
if (!row || !verifyPassword(password, row.pass_salt, row.pass_hash)) {
noteAttempt(key)
return json(res, 401, { ok: false, error: '用户名或密码不对' })
}
if (row.disabled) return json(res, 403, { ok: false, error: '这个账号已被停用' })
resetAttempts(key)
const sid = createSession(db, row.id)
return json(res, 200, { ok: true, user: userView(sid, row) }, { 'set-cookie': cookieHeader(sid, 30 * 24 * 3600) })
}
if (pathname === '/api/logout' && method === 'POST') {
const cookies = parseCookies(req.headers.cookie)
destroySession(db, cookies[SESSION_COOKIE])
return json(res, 200, { ok: true }, { 'set-cookie': clearCookieHeader() })
}
const user = currentUser(req)
if (!user) return json(res, 401, { ok: false, error: '没有登录,刷新页面重新登录一下' })
if (pathname === '/api/me') {
const uses = db.prepare('SELECT COUNT(*) AS n FROM uses WHERE user_id = ?').get(user.id).n
return json(res, 200, { ok: true, user: userView(null, user), uses })
}
if (pathname === '/api/consume' && method === 'POST') {
const body = await readJson(req)
const tool = String(body.tool || '').slice(0, 60) || 'unknown'
const res1 = consume(db, user.id, tool)
if (!res1.ok) {
const message = res1.reason === 'insufficient' ? '积分不够了,用 CDK 兑换一些再继续' : '账号不存在了'
return json(res, 402, { ok: false, error: message, user: publicUser(res1.user), cost: COST_PER_USE })
}
return json(res, 200, { ok: true, user: userView(null, res1.user), cost: COST_PER_USE })
}
if (pathname === '/api/redeem' && method === 'POST') {
const body = await readJson(req)
const code = String(body.code || '').trim().toUpperCase()
if (!code) return json(res, 400, { ok: false, error: '先填 CDK' })
const out = redeemCode(db, code, user.id)
if (!out.ok) {
const map = { missing: '这个 CDK 不存在,检查一下有没有打错', used: '这个 CDK 已经被用过了' }
return json(res, 400, { ok: false, error: map[out.reason] || '兑换失败' })
}
return json(res, 200, { ok: true, credits: out.credits, user: userView(null, out.user) })
}
if (pathname === '/api/me/password' && method === 'POST') {
const body = await readJson(req)
const current = String(body.current || '')
const next = String(body.next || '')
if (!verifyPassword(current, user.pass_salt, user.pass_hash)) return json(res, 401, { ok: false, error: '当前密码不对' })
if (next.length < 6) return json(res, 400, { ok: false, error: '新密码至少 6 位' })
const { salt, hash } = hashPassword(next)
db.prepare('UPDATE users SET pass_hash = ?, pass_salt = ? WHERE id = ?').run(hash, salt, user.id)
const cookies = parseCookies(req.headers.cookie)
destroyUserSessions(db, user.id, cookies[SESSION_COOKIE])
return json(res, 200, { ok: true })
}
// ---- 管理后台 ----
if (pathname.startsWith('/api/admin/')) {
if (user.role !== 'admin') return json(res, 403, { ok: false, error: '只有管理员能进' })
if (pathname === '/api/admin/overview') {
const stats = codeStats(db)
const sum = db.prepare('SELECT COUNT(*) AS users, COALESCE(SUM(credits),0) AS credits FROM users').get()
return json(res, 200, {
ok: true,
cost: COST_PER_USE,
startCredits: START_CREDITS,
users: sum.users,
credits: sum.credits,
codes: stats,
recentUses: recentUses(db, 20)
})
}
if (pathname === '/api/admin/users' && method === 'GET') {
return json(res, 200, {
ok: true,
users: listUsers(db).map((u) => ({
id: u.id,
username: u.username,
role: u.role,
credits: u.credits,
disabled: Boolean(u.disabled),
createdAt: u.created_at,
useCount: u.use_count,
lastUsed: u.last_used
}))
})
}
if (pathname === '/api/admin/users/credits' && method === 'POST') {
const body = await readJson(req)
const id = Number(body.id)
const delta = Number(body.delta)
const target = getUser(db, id)
if (!target) return json(res, 404, { ok: false, error: '没有这个用户' })
if (!Number.isFinite(delta) || delta === 0) return json(res, 400, { ok: false, error: '改动值不对' })
const row = addCredits(db, id, Math.trunc(delta))
return json(res, 200, { ok: true, user: { id: row.id, username: row.username, credits: row.credits } })
}
if (pathname === '/api/admin/users/disabled' && method === 'POST') {
const body = await readJson(req)
const id = Number(body.id)
const disabled = Boolean(body.disabled)
if (id === user.id) return json(res, 400, { ok: false, error: '不能停用自己' })
const target = getUser(db, id)
if (!target) return json(res, 404, { ok: false, error: '没有这个用户' })
db.prepare('UPDATE users SET disabled = ? WHERE id = ?').run(disabled ? 1 : 0, id)
if (disabled) destroyUserSessions(db, id)
return json(res, 200, { ok: true })
}
if (pathname === '/api/admin/codes' && method === 'GET') {
return json(res, 200, { ok: true, codes: listCodes(db, 200) })
}
if (pathname === '/api/admin/codes' && method === 'POST') {
const body = await readJson(req)
const count = Math.min(Math.max(Number(body.count) || 1, 1), 200)
const credits = Math.min(Math.max(Number(body.credits) || 100, 1), 100000)
const out = []
for (let i = 0; i < count; i++) {
let code = newCode()
for (let tries = 0; tries < 5; tries++) {
try {
out.push(createCode(db, { code, credits, createdBy: user.id }))
break
} catch {
code = newCode()
}
}
}
return json(res, 200, { ok: true, created: out.map((c) => ({ code: c.code, credits: c.credits })) })
}
}
return json(res, 404, { ok: false, error: '没有这个接口' })
}
const server = createServer(async (req, res) => {
const started = Date.now()
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`)
try {
if (url.pathname.startsWith('/api/')) return await handleApi(req, res, url.pathname)
return await serveStatic(req, res, url.pathname)
} catch (error) {
if (!res.headersSent) json(res, 500, { ok: false, error: String(error?.message || error) })
else res.end()
} finally {
if (process.env.DEVBOX_LOG !== '0') {
const ms = Date.now() - started
if (ms > 800) console.log(`${req.method} ${url.pathname} ${ms}ms`)
}
}
})
server.listen(PORT, HOST, () => {
console.log(`DevBox 在 http://${HOST}:${PORT} 上跑着(数据:${DATA_DIR})`)
if (countUsers(db) === 0) console.log('还没有账号:第一个注册的人会自动成为管理员。')
})
for (const sig of ['SIGINT', 'SIGTERM']) {
process.on(sig, () => {
server.close(() => process.exit(0))
setTimeout(() => process.exit(0), 3000).unref()
})
}