feat: 全面升级——后台优化 / 动态配置 / 个人中心 / OSS 存储

- OSS 文件存储(RustFS / S3 v4 兼容,零依赖手写 SigV4):
  上传/列表/删除走桶 arcticnewone,/uploads 代理服务 + 本地回退;
  server/utils/sigv4.ts 纯函数 + AWS 测试向量验证
- 业务动态配置:settings 表 + /api/settings(公开) + /api/admin/settings(PATCH),
  useSiteSettings 组合式,footer/contact/tools/app.vue/侧边栏/工具页全部接入,
  后台 /admin/settings 修改前台即时生效(站点/联系/社交/工具箱/页脚/SEO)
- 后台全面优化:Admin* 设计系统(按钮/输入/表单/卡片/徽标/弹窗/确认/空态/骨架/
  分页/页头/Toast)14 组件;Dashboard 增强;各列表页搜索/筛选/批量删除/分页;
  布局与侧边栏分组;统一 toast/确认反馈
- 个人中心全新重设计:顶部资料卡 + 统计、精致化改密/删号(二次确认)、
  收藏封面网格、评论卡片、移动端适配
- deploy.sh 支持 OSS 凭据注入(NUXT_OSS_*);.env.example 更新
- 测试 17 例全过(含 SigV4 AWS 向量、settings 默认结构)
This commit is contained in:
2026-08-06 18:40:17 +08:00
parent 685c7b51d1
commit 5a7ad8de11
55 changed files with 3857 additions and 1993 deletions
+17
View File
@@ -28,6 +28,15 @@ export interface AppConfig {
adminEmails: string[]
/** 首次初始化时预置 admin 账号的密码(NUXT_ADMIN_INITIAL_PASSWORD),未设则不预置 */
adminInitialPassword: string
/** OSS 文件存储(RustFS / S3 v4 兼容) */
oss: {
endpoint: string
accessKey: string
secretKey: string
bucket: string
region: string
publicBase: string
}
siteUrl: string
}
@@ -49,6 +58,14 @@ export function getConfig(): AppConfig {
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
adminInitialPassword: String((c as any).adminInitialPassword || ''),
oss: {
endpoint: String((c as any).ossEndpoint || '').replace(/^https?:\/\//, '').replace(/\/$/, ''),
accessKey: String((c as any).ossAccessKey || ''),
secretKey: String((c as any).ossSecretKey || ''),
bucket: String((c as any).ossBucket || ''),
region: String((c as any).ossRegion || 'us-east-1'),
publicBase: String((c as any).ossPublicBase || '').replace(/\/$/, ''),
},
siteUrl: String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, ''),
}
}
+6
View File
@@ -167,6 +167,12 @@ function migrate(db: Database.Database): void {
);
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
-- 业务动态配置(后台可改;value 为 JSON 字符串)
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`)
// 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS)
+121
View File
@@ -0,0 +1,121 @@
import { getConfig } from './config'
import { sha256Hex, signRequest } from './sigv4'
/**
* 极简 S3 客户端(RustFS / S3 v4 兼容,零第三方依赖)。
* 手写 AWS SigV4 签名:putObject / getObject / deleteObject / listObjectsV2。
* 配置来自 env(NUXT_OSS_*),凭据绝不写入仓库。
*/
export interface OssConfig {
endpoint: string
accessKey: string
secretKey: string
bucket: string
region: string
publicBase: string
}
export function getOssConfig(): OssConfig | null {
const { oss } = getConfig()
if (!oss.endpoint || !oss.accessKey || !oss.secretKey || !oss.bucket) return null
return oss
}
export const isOssConfigured = (): boolean => getOssConfig() !== null
const encodeKey = (key: string) => key.split('/').map(encodeURIComponent).join('/')
const qs = (q: Record<string, string>) => {
const s = Object.keys(q)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(q[k]))}`)
.join('&')
return s ? `?${s}` : ''
}
async function s3Request(
method: string,
key: string,
opts: { query?: Record<string, string>; body?: string | Buffer; contentType?: string; isList?: boolean } = {},
): Promise<Response> {
const cfg = getOssConfig()
if (!cfg) throw new Error('OSS 未配置')
const path = opts.isList ? `/${cfg.bucket}` : `/${cfg.bucket}/${encodeKey(key)}`
const body = opts.body ?? ''
const bodyHash = sha256Hex(body)
const date = new Date().toISOString()
const headers: Record<string, string> = {
host: cfg.endpoint,
'x-amz-content-sha256': bodyHash,
...(opts.contentType ? { 'content-type': opts.contentType } : {}),
}
const { authorization, amzDate } = signRequest({
method,
path,
query: opts.query ?? {},
headers,
bodyHash,
date,
accessKey: cfg.accessKey,
secretKey: cfg.secretKey,
region: cfg.region,
})
headers['x-amz-date'] = amzDate
const url = `https://${cfg.endpoint}${path}${qs(opts.query ?? {})}`
return fetch(url, {
method,
headers: { ...headers, authorization },
body: method === 'GET' || method === 'DELETE' ? undefined : body,
})
}
// ---------- 对象操作 ----------
export async function putObject(key: string, body: Buffer, contentType: string): Promise<string> {
const res = await s3Request('PUT', key, { body, contentType })
if (!res.ok) throw new Error(`OSS 上传失败: ${res.status}`)
return key
}
export async function getObject(key: string): Promise<Response | null> {
const res = await s3Request('GET', key)
if (res.status === 404) return null
if (!res.ok) throw new Error(`OSS 读取失败: ${res.status}`)
return res
}
export async function deleteObject(key: string): Promise<boolean> {
const res = await s3Request('DELETE', key)
return res.ok || res.status === 204
}
export interface OssFile {
name: string
size: number
modified: string
url: string
}
export async function listObjectsV2(prefix = ''): Promise<OssFile[]> {
const res = await s3Request('GET', '', {
isList: true,
query: { 'list-type': '2', prefix, 'max-keys': '1000' },
})
if (!res.ok) throw new Error(`OSS 列表失败: ${res.status}`)
const xml = await res.text()
const files: OssFile[] = []
const contentRe = /<Contents>([\s\S]*?)<\/Contents>/g
let m: RegExpExecArray | null
while ((m = contentRe.exec(xml))) {
const item = m[1]
const name = /<Key>([\s\S]*?)<\/Key>/.exec(item)?.[1]
if (!name) continue
const size = Number(/<Size>([\s\S]*?)<\/Size>/.exec(item)?.[1] || 0)
const modified = /<LastModified>([\s\S]*?)<\/LastModified>/.exec(item)?.[1] || ''
files.push({ name, size, modified, url: `/uploads/${encodeKey(name)}` })
}
files.sort((a, b) => b.modified.localeCompare(a.modified))
return files
}
+45
View File
@@ -0,0 +1,45 @@
import { getDb } from './db'
import { defaultSettings, type SiteSettings } from '../../app/config/site'
/**
* 站点业务动态配置。
* DB settings 表优先,未配置项回退到默认值(app/config/site.ts)。
* 后台 /admin/settings 可实时修改,前台经 /api/settings 读取。
*/
// 深拷贝默认值,避免修改默认对象
function cloneDefaults(): SiteSettings {
return JSON.parse(JSON.stringify(defaultSettings)) as SiteSettings
}
/** 按点分路径设置合并后的值(如 site.name -> merged.site.name) */
function setPath(target: Record<string, unknown>, path: string, value: unknown): void {
const parts = path.split('.')
let cur: Record<string, unknown> = target
for (let i = 0; i < parts.length - 1; i += 1) {
cur = cur[parts[i]] as Record<string, unknown>
if (!cur) return
}
cur[parts[parts.length - 1]] = value
}
export function getSettings(): SiteSettings {
const merged = cloneDefaults()
const rows = getDb().prepare('SELECT key, value FROM settings').all() as Array<{ key: string; value: string }>
for (const row of rows) {
try {
setPath(merged as unknown as Record<string, unknown>, row.key, JSON.parse(row.value))
} catch {
// 单个配置损坏不影响其余
}
}
return merged
}
export function updateSetting(key: string, value: unknown): void {
getDb()
.prepare(
'INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
)
.run(key, JSON.stringify(value))
}
+60
View File
@@ -0,0 +1,60 @@
import { createHmac, createHash } from 'node:crypto'
/**
* AWS SigV4 签名(S3 v4 兼容,纯函数、无 Nuxt 依赖,便于单元测试)。
* 参考 AWS 文档 CanonicalRequest 算法。
*/
export const sha256Hex = (data: string | Buffer) => createHash('sha256').update(data).digest('hex')
const hmac = (key: Buffer | string, data: string) => createHmac('sha256', key).update(data).digest()
export interface SignRequestInput {
method: string
path: string
query: Record<string, string>
/** 参与签名的头(key 小写),如 host / x-amz-date / x-amz-content-sha256 */
headers: Record<string, string>
bodyHash: string
date: string // ISO 8601,如 2013-05-24T00:00:00.000Z
accessKey: string
secretKey: string
region: string
service?: string
}
export function signRequest(opts: SignRequestInput): { authorization: string; amzDate: string } {
const service = opts.service ?? 's3'
const amzDate = opts.date.replace(/[:-]|\.\d{3}/g, '')
const datestamp = opts.date.slice(0, 10).replace(/-/g, '')
const headerNames = Object.keys(opts.headers).map((h) => h.toLowerCase()).sort()
const canonicalHeaders = headerNames.map((h) => `${h}:${String(opts.headers[h]).trim()}\n`).join('')
const signedHeaders = headerNames.join(';')
const canonicalQuery = Object.keys(opts.query)
.sort()
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(opts.query[k]))}`)
.join('&')
const canonicalRequest = [
opts.method,
opts.path,
canonicalQuery,
canonicalHeaders,
signedHeaders,
opts.bodyHash,
].join('\n')
const scope = `${datestamp}/${opts.region}/${service}/aws4_request`
const stringToSign = `AWS4-HMAC-SHA256\n${amzDate}\n${scope}\n${sha256Hex(canonicalRequest)}`
const kDate = hmac(`AWS4${opts.secretKey}`, datestamp)
const kRegion = hmac(kDate, opts.region)
const kService = hmac(kRegion, service)
const kSigning = hmac(kService, 'aws4_request')
const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex')
return {
authorization: `AWS4-HMAC-SHA256 Credential=${opts.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
amzDate,
}
}