feat(admin): 添加 S3 兼容存储备份功能
- 新增 S3 配置管理页面,支持 AWS S3、Cloudflare R2、MinIO 等兼容存储 - 实现 S3 客户端工具类,使用 aws4fetch 进行签名和上传 - 添加手动触发备份功能,将评论、配置和统计数据打包为 JSON 上传至 S3 - 在管理后台数据管理页面集成 S3 配置表单和备份操作按钮 - 新增相关 API 端点用于获取/保存 S3 配置及触发备份
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
"wrangler": "^4.63.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"aws4fetch": "^1.0.20",
|
||||
"hono": "^4.11.3",
|
||||
"marked": "^17.0.1",
|
||||
"nodemailer": "^7.0.12",
|
||||
|
||||
38
cwd-api/src/api/admin/s3Settings.ts
Normal file
38
cwd-api/src/api/admin/s3Settings.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Context } from 'hono';
|
||||
import { Bindings } from '../../bindings';
|
||||
import { loadS3Settings, saveS3Settings } from '../../utils/s3Settings';
|
||||
|
||||
export async function getS3Settings(c: Context<{ Bindings: Bindings }>) {
|
||||
try {
|
||||
const settings = await loadS3Settings(c.env);
|
||||
// Hide secret key for security in UI if needed, but usually user needs to edit it.
|
||||
// For now, return it as is, or maybe mask it partially?
|
||||
// User usually expects to see the inputs.
|
||||
return c.json(settings);
|
||||
} catch (e: any) {
|
||||
return c.json({ message: e.message || '加载 S3 配置失败' }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateS3Settings(c: Context<{ Bindings: Bindings }>) {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : '';
|
||||
const accessKeyId = typeof body.accessKeyId === 'string' ? body.accessKeyId.trim() : '';
|
||||
const secretAccessKey = typeof body.secretAccessKey === 'string' ? body.secretAccessKey.trim() : '';
|
||||
const bucket = typeof body.bucket === 'string' ? body.bucket.trim() : '';
|
||||
const region = typeof body.region === 'string' ? body.region.trim() : 'auto';
|
||||
|
||||
await saveS3Settings(c.env, {
|
||||
endpoint,
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
bucket,
|
||||
region,
|
||||
});
|
||||
|
||||
return c.json({ message: '保存成功' });
|
||||
} catch (e: any) {
|
||||
return c.json({ message: e.message || '保存失败' }, 500);
|
||||
}
|
||||
}
|
||||
54
cwd-api/src/api/admin/triggerS3Backup.ts
Normal file
54
cwd-api/src/api/admin/triggerS3Backup.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { Context } from 'hono';
|
||||
import { Bindings } from '../../bindings';
|
||||
import { loadS3Settings } from '../../utils/s3Settings';
|
||||
import { S3Client } from '../../utils/s3';
|
||||
import { getConfigs } from './exportConfig';
|
||||
import { getStatsData } from './exportStats';
|
||||
|
||||
export async function triggerS3Backup(c: Context<{ Bindings: Bindings }>) {
|
||||
try {
|
||||
// 1. Load S3 Settings
|
||||
const settings = await loadS3Settings(c.env);
|
||||
if (!settings.endpoint || !settings.bucket || !settings.accessKeyId || !settings.secretAccessKey) {
|
||||
return c.json({ message: 'S3 配置不完整,请先配置 S3 信息' }, 400);
|
||||
}
|
||||
|
||||
// 2. Gather Backup Data (Logic from exportBackup.ts)
|
||||
const { results: comments } = await c.env.CWD_DB.prepare('SELECT * FROM Comment ORDER BY priority DESC, created DESC').all();
|
||||
const configs = await getConfigs(c.env);
|
||||
const stats = await getStatsData(c.env);
|
||||
|
||||
const backupData = {
|
||||
version: '1.0',
|
||||
timestamp: Date.now(),
|
||||
comments: comments,
|
||||
settings: configs,
|
||||
page_stats: stats.page_stats,
|
||||
page_visit_daily: stats.page_visit_daily,
|
||||
likes: stats.likes,
|
||||
};
|
||||
|
||||
const jsonString = JSON.stringify(backupData, null, 2);
|
||||
const dateStr = new Date().toISOString().split('T')[0];
|
||||
const fileName = `cwd-backup-${dateStr}-${Date.now()}.json`;
|
||||
|
||||
// 3. Upload to S3
|
||||
const s3 = new S3Client({
|
||||
endpoint: settings.endpoint,
|
||||
accessKeyId: settings.accessKeyId,
|
||||
secretAccessKey: settings.secretAccessKey,
|
||||
bucket: settings.bucket,
|
||||
region: settings.region,
|
||||
});
|
||||
|
||||
await s3.putObject(fileName, jsonString);
|
||||
|
||||
return c.json({
|
||||
message: '备份成功',
|
||||
file: fileName,
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error('S3 Backup Error:', e);
|
||||
return c.json({ message: e.message || 'S3 备份失败' }, 500);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ import { listLikes } from './api/admin/listLikes';
|
||||
import { getLikeStats } from './api/admin/likeStats';
|
||||
import { getFeatureSettings, updateFeatureSettings } from './api/admin/featureSettings';
|
||||
import { getTelegramSettings, updateTelegramSettings, setupTelegramWebhook, testTelegramMessage } from './api/admin/telegramSettings';
|
||||
import { getS3Settings, updateS3Settings } from './api/admin/s3Settings';
|
||||
import { triggerS3Backup } from './api/admin/triggerS3Backup';
|
||||
import { telegramWebhook } from './api/telegram/webhook';
|
||||
import { ensureSchema } from './utils/dbMigration';
|
||||
|
||||
@@ -340,6 +342,10 @@ app.put('/admin/settings/telegram', updateTelegramSettings);
|
||||
app.post('/admin/settings/telegram/setup', setupTelegramWebhook);
|
||||
app.post('/admin/settings/telegram/test', testTelegramMessage);
|
||||
|
||||
app.get('/admin/settings/s3', getS3Settings);
|
||||
app.put('/admin/settings/s3', updateS3Settings);
|
||||
app.post('/admin/backup/s3', triggerS3Backup);
|
||||
|
||||
app.get('/admin/settings/admin-display', async (c) => {
|
||||
try {
|
||||
const settings = await loadAdminDisplaySettings(c.env);
|
||||
|
||||
52
cwd-api/src/utils/s3.ts
Normal file
52
cwd-api/src/utils/s3.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { AwsClient } from 'aws4fetch';
|
||||
|
||||
export interface S3Config {
|
||||
endpoint: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
bucket: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export class S3Client {
|
||||
private client: AwsClient;
|
||||
private bucket: string;
|
||||
private endpoint: string;
|
||||
|
||||
constructor(config: S3Config) {
|
||||
this.client = new AwsClient({
|
||||
accessKeyId: config.accessKeyId,
|
||||
secretAccessKey: config.secretAccessKey,
|
||||
region: config.region || 'auto',
|
||||
service: 's3',
|
||||
});
|
||||
this.bucket = config.bucket;
|
||||
// Ensure endpoint doesn't have trailing slash
|
||||
this.endpoint = config.endpoint.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
async putObject(key: string, body: string | Uint8Array | Blob) {
|
||||
const url = `${this.endpoint}/${this.bucket}/${key}`;
|
||||
// Some S3 compatible storages need path style access
|
||||
// If endpoint is like https://s3.amazonaws.com, it might need virtual host style
|
||||
// But for broad compatibility (MinIO, R2, etc.), path style is often safer if endpoint is custom.
|
||||
// However, aws4fetch handles signing.
|
||||
|
||||
// Let's try to construct URL carefully.
|
||||
// If endpoint includes bucket in hostname, we shouldn't add it to path.
|
||||
// But assuming user provides a generic endpoint (e.g. https://<account>.r2.cloudflarestorage.com)
|
||||
// We will append bucket to path: https://<endpoint>/<bucket>/<key>
|
||||
|
||||
const res = await this.client.fetch(url, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`S3 Upload Failed: ${res.status} ${res.statusText} - ${text}`);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
}
|
||||
49
cwd-api/src/utils/s3Settings.ts
Normal file
49
cwd-api/src/utils/s3Settings.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Bindings } from '../bindings';
|
||||
|
||||
const S3_CONFIG_KEY = 's3_config';
|
||||
|
||||
export interface S3Settings {
|
||||
endpoint: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
bucket: string;
|
||||
region: string;
|
||||
}
|
||||
|
||||
export async function loadS3Settings(env: Bindings): Promise<S3Settings> {
|
||||
await env.CWD_DB.prepare('CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)').run();
|
||||
const row = await env.CWD_DB.prepare('SELECT value FROM Settings WHERE key = ?')
|
||||
.bind(S3_CONFIG_KEY)
|
||||
.first<{ value: string }>();
|
||||
|
||||
const defaults: S3Settings = {
|
||||
endpoint: '',
|
||||
accessKeyId: '',
|
||||
secretAccessKey: '',
|
||||
bucket: '',
|
||||
region: 'auto',
|
||||
};
|
||||
|
||||
if (!row || !row.value) {
|
||||
return defaults;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(row.value);
|
||||
return {
|
||||
endpoint: parsed.endpoint || '',
|
||||
accessKeyId: parsed.accessKeyId || '',
|
||||
secretAccessKey: parsed.secretAccessKey || '',
|
||||
bucket: parsed.bucket || '',
|
||||
region: parsed.region || 'auto',
|
||||
};
|
||||
} catch {
|
||||
return defaults;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveS3Settings(env: Bindings, settings: S3Settings) {
|
||||
await env.CWD_DB.prepare('CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)').run();
|
||||
const value = JSON.stringify(settings);
|
||||
await env.CWD_DB.prepare('REPLACE INTO Settings (key, value) VALUES (?, ?)').bind(S3_CONFIG_KEY, value).run();
|
||||
}
|
||||
Reference in New Issue
Block a user