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:
@@ -0,0 +1,10 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getSettings } from '../../utils/settings'
|
||||
|
||||
/**
|
||||
* 后台读取站点配置
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
return getSettings()
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getSettings, updateSetting } from '../../utils/settings'
|
||||
import { writeAudit } from '../../utils/audit'
|
||||
|
||||
/**
|
||||
* 后台更新站点配置。
|
||||
* body: { settings: Partial<SiteSettings> } —— 按叶节点展开写库,未提供的项保持不变。
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event)
|
||||
const body = await readBody(event)
|
||||
|
||||
const patch = body?.settings
|
||||
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
|
||||
throw createError({ statusCode: 400, message: '缺少配置内容', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
// 将嵌套对象展开为点分叶键(数组整体作为一个值)
|
||||
const flatten = (obj: Record<string, unknown>, prefix = '', out: Record<string, unknown> = {}) => {
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const key = prefix ? `${prefix}.${k}` : k
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
||||
flatten(v as Record<string, unknown>, key, out)
|
||||
} else {
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const flat = flatten(patch)
|
||||
const keys = Object.keys(flat)
|
||||
if (keys.length === 0) {
|
||||
throw createError({ statusCode: 400, message: '没有可更新的配置', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
for (const [k, v] of Object.entries(flat)) {
|
||||
updateSetting(k, v)
|
||||
}
|
||||
|
||||
writeAudit(event, 'update', 'settings', keys.slice(0, 5).join(','))
|
||||
return { ok: true, settings: getSettings() }
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getConfig } from '../../utils/config'
|
||||
import { getOssConfig, putObject } from '../../utils/s3'
|
||||
import { writeAudit } from '../../utils/audit'
|
||||
|
||||
const MAX_SIZE = 8 * 1024 * 1024 // 8MB
|
||||
@@ -17,8 +18,9 @@ const EXT_BY_TYPE: Record<string, string> = {
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads),
|
||||
* 通过 /uploads/<name> 对外提供。
|
||||
* 后台图片上传:
|
||||
* - OSS 已配置 -> 上传到桶 arcticnewone(key: images/<name>),URL /uploads/images/<name>
|
||||
* - OSS 未配置 -> 回退写入本地 /data/uploads(兼容无 OSS 环境)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event)
|
||||
@@ -39,10 +41,19 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
|
||||
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
|
||||
|
||||
const oss = getOssConfig()
|
||||
if (oss) {
|
||||
const key = `images/${name}`
|
||||
await putObject(key, Buffer.from(file.data), type)
|
||||
writeAudit(event, 'upload', `oss:${key}`)
|
||||
return { ok: true, url: `/uploads/images/${name}` }
|
||||
}
|
||||
|
||||
// 本地回退(保留历史行为,兼容无 OSS 环境)
|
||||
const dir = join(dirname(getConfig().dbPath), 'uploads')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(join(dir, name), file.data)
|
||||
|
||||
writeAudit(event, 'upload', `upload:${name}`)
|
||||
return { ok: true, url: `/uploads/${name}` }
|
||||
writeFileSync(join(dir, name), Buffer.from(file.data))
|
||||
writeAudit(event, 'upload', `local:${name}`)
|
||||
return { ok: true, url: `/uploads/${name}` }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { getQuery, createError } from 'h3'
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getConfig } from '../../utils/config'
|
||||
import { getOssConfig, deleteObject } from '../../utils/s3'
|
||||
import { writeAudit } from '../../utils/audit'
|
||||
import { unlinkSync, existsSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
|
||||
/**
|
||||
* 后台删除上传的文件(DELETE /api/admin/uploads?name=<key>)
|
||||
* - OSS 已配置 -> deleteObject(name)(name 为完整对象 key,如 images/abc.png)
|
||||
* - 否则回退删除本地文件
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const q = getQuery(event)
|
||||
const name = String(q?.name ?? '')
|
||||
|
||||
if (!name || name.includes('..')) {
|
||||
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const oss = getOssConfig()
|
||||
if (oss) {
|
||||
deleteObject(name).then(() => writeAudit(event, 'delete', `oss:${name}`))
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
// 本地回退:仅允许纯文件名
|
||||
const basename = name.split('/').pop() ?? ''
|
||||
if (!basename || basename.includes('\\')) {
|
||||
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const filePath = join(dirname(getConfig().dbPath), 'uploads', basename)
|
||||
if (!existsSync(filePath)) {
|
||||
throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
unlinkSync(filePath)
|
||||
writeAudit(event, 'delete', `local:${basename}`)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -1,15 +1,24 @@
|
||||
import { requireAdmin } from '../../utils/auth'
|
||||
import { getConfig } from '../../utils/config'
|
||||
import { getOssConfig, listObjectsV2 } from '../../utils/s3'
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
|
||||
/**
|
||||
* 后台图片管理:列出 /data/uploads 下的文件
|
||||
* 后台图片管理:列出上传的文件
|
||||
* - OSS 已配置 -> ListObjectsV2(prefix=images/)
|
||||
* - 否则回退本地 /data/uploads
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event)
|
||||
const dir = join(dirname(getConfig().dbPath), 'uploads')
|
||||
|
||||
const oss = getOssConfig()
|
||||
if (oss) {
|
||||
const files = await listObjectsV2('images/')
|
||||
return { files, storage: 'oss' }
|
||||
}
|
||||
|
||||
const dir = join(dirname(getConfig().dbPath), 'uploads')
|
||||
const files: Array<{ name: string; size: number; modified: string; url: string }> = []
|
||||
try {
|
||||
for (const name of readdirSync(dir)) {
|
||||
@@ -21,7 +30,6 @@ export default defineEventHandler((event) => {
|
||||
} catch {
|
||||
// 目录可能尚不存在
|
||||
}
|
||||
|
||||
files.sort((a, b) => b.modified.localeCompare(a.modified))
|
||||
return { files }
|
||||
return { files, storage: 'local' }
|
||||
})
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { createError } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getConfig } from '../../../utils/config'
|
||||
import { writeAudit } from '../../../utils/audit'
|
||||
import { unlinkSync, existsSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
|
||||
/**
|
||||
* 后台删除上传的图片
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const name = getRouterParam(event, 'name') ?? ''
|
||||
|
||||
// 防目录穿越:仅允许纯文件名
|
||||
if (!name || name.includes('/') || name.includes('\\') || name.includes('..')) {
|
||||
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const filePath = join(dirname(getConfig().dbPath), 'uploads', name)
|
||||
if (!existsSync(filePath)) {
|
||||
throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
unlinkSync(filePath)
|
||||
writeAudit(event, 'delete', `upload:${name}`)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { getSettings } from '../utils/settings'
|
||||
|
||||
/**
|
||||
* 站点公开配置(前台读取,SSR 友好)
|
||||
*/
|
||||
export default defineEventHandler(() => {
|
||||
return getSettings()
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getConfig } from '../utils/config'
|
||||
import { getSettings } from '../utils/settings'
|
||||
import { listArticles } from '../utils/content'
|
||||
|
||||
const escapeXml = (s: string) =>
|
||||
@@ -13,6 +14,7 @@ const escapeXml = (s: string) =>
|
||||
*/
|
||||
export default defineEventHandler(() => {
|
||||
const { siteUrl } = getConfig()
|
||||
const { site } = getSettings()
|
||||
const articles = listArticles({ publishedOnly: true })
|
||||
|
||||
const items = articles
|
||||
@@ -36,9 +38,9 @@ export default defineEventHandler(() => {
|
||||
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||
<channel>
|
||||
<title>ArcticNewOne</title>
|
||||
<title>${escapeXml(site.name)}</title>
|
||||
<link>${siteUrl}</link>
|
||||
<description>北极新一工作室的最新动态与洞察</description>
|
||||
<description>${escapeXml(site.description.zh)}</description>
|
||||
<language>zh-cn</language>
|
||||
<atom:link href="${siteUrl}/feed.xml" rel="self" type="application/rss+xml"/>
|
||||
${items}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createError } from 'h3'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import { join, dirname, normalize } from 'node:path'
|
||||
import { getConfig } from '../../utils/config'
|
||||
import { getOssConfig, getObject } from '../../utils/s3'
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
@@ -13,27 +14,46 @@ const MIME: Record<string, string> = {
|
||||
avif: 'image/avif',
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务上传的图片(存于 PVC uploads 目录)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const path = getRouterParam(event, 'path') ?? ''
|
||||
const base = normalize(join(dirname(getConfig().dbPath), 'uploads'))
|
||||
const filePath = normalize(join(base, path))
|
||||
const mimeFromName = (name: string) => MIME[name.split('.').pop()?.toLowerCase() ?? ''] || 'application/octet-stream'
|
||||
|
||||
// 防目录穿越
|
||||
if (!filePath.startsWith(base + '/') && filePath !== base) {
|
||||
/**
|
||||
* 服务上传的图片:
|
||||
* - OSS 已配置 -> 从桶 arcticnewone 拉取(key 为 /uploads/<path> 的 path)
|
||||
* - OSS 无该对象或未配置 -> 回退读取本地 /data/uploads(兼容历史已上传内容)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const path = getRouterParam(event, 'path') ?? ''
|
||||
|
||||
const oss = getOssConfig()
|
||||
if (oss) {
|
||||
try {
|
||||
const res = await getObject(path)
|
||||
if (res) {
|
||||
return new Response(res.body, {
|
||||
headers: {
|
||||
'Content-Type': res.headers.get('content-type') || mimeFromName(path),
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[uploads] oss read failed, fallback to local:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// 本地回退
|
||||
const base = normalize(join(dirname(getConfig().dbPath), 'uploads'))
|
||||
const filePath = normalize(join(base, path.split('/').join('/')))
|
||||
if (!filePath.startsWith(base + '/')) {
|
||||
throw createError({ statusCode: 403, message: 'Forbidden' })
|
||||
}
|
||||
if (!existsSync(filePath)) {
|
||||
throw createError({ statusCode: 404, message: 'Not Found' })
|
||||
}
|
||||
|
||||
const ext = filePath.split('.').pop()?.toLowerCase() ?? ''
|
||||
const data = readFileSync(filePath)
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: {
|
||||
'Content-Type': MIME[ext] || 'application/octet-stream',
|
||||
'Content-Type': mimeFromName(filePath),
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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(/\/$/, ''),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user