Merge branch 'feature/m14-backup-admin' - M14 backup & admin
This commit is contained in:
47
components/admin/BackupCreateButton.tsx
Normal file
47
components/admin/BackupCreateButton.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export function BackupCreateButton() {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function onCreate() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res = await fetch('/api/admin/backups', { method: 'POST' });
|
||||
setLoading(false);
|
||||
if (res.ok) {
|
||||
router.refresh();
|
||||
} else {
|
||||
const b = (await res.json().catch(() => null)) as {
|
||||
error?: { message?: string };
|
||||
} | null;
|
||||
setError(b?.error?.message ?? '作成に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-white p-4 shadow-sm">
|
||||
<p className="text-sm text-gray-600">
|
||||
DBファイル + uploadsディレクトリをZIP化してバックアップを作成します。
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreate}
|
||||
disabled={loading}
|
||||
className="mt-2 rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50"
|
||||
data-testid="create-backup"
|
||||
>
|
||||
{loading ? '作成中...' : 'バックアップ作成'}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="mt-2 text-sm text-red-600" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -25,6 +25,7 @@ import { MeetingService } from '@/services/MeetingService';
|
||||
import { MeetingRepository } from '@/repositories/MeetingRepository';
|
||||
import { SearchService } from '@/services/SearchService';
|
||||
import { DashboardService } from '@/services/DashboardService';
|
||||
import { BackupService } from '@/services/BackupService';
|
||||
|
||||
/**
|
||||
* Route Handler用に各Repository/Serviceを構築するファクトリ。
|
||||
@ -168,6 +169,13 @@ export function createDashboardService(): DashboardService {
|
||||
);
|
||||
}
|
||||
|
||||
export function createBackupService(): BackupService {
|
||||
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
|
||||
const uploadsDir = process.env.UPLOADS_PATH ?? './data/uploads';
|
||||
const backupsDir = './backups';
|
||||
return new BackupService(dbPath, uploadsDir, backupsDir);
|
||||
}
|
||||
|
||||
export function createUserRepository(): UserRepository {
|
||||
return new UserRepository(getDb());
|
||||
}
|
||||
|
||||
2
package-lock.json
generated
2
package-lock.json
generated
@ -11,6 +11,7 @@
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"better-sqlite3": "^11.3.0",
|
||||
"fflate": "^0.8.3",
|
||||
"next": "^15.1.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
@ -5058,7 +5059,6 @@
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/file-entry-cache": {
|
||||
|
||||
@ -27,6 +27,7 @@
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"better-sqlite3": "^11.3.0",
|
||||
"fflate": "^0.8.3",
|
||||
"next": "^15.1.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
|
||||
@ -8,6 +8,7 @@ export default defineConfig({
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: 'html',
|
||||
globalSetup: './tests/e2e/globalSetup.ts',
|
||||
use: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
trace: 'on-first-retry',
|
||||
|
||||
112
services/BackupService.ts
Normal file
112
services/BackupService.ts
Normal file
@ -0,0 +1,112 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { zipSync } from 'fflate';
|
||||
import { ForbiddenError, NotFoundError } from '@/lib/errors';
|
||||
import type { UserRole } from '@/lib/types';
|
||||
|
||||
export interface BackupActor {
|
||||
id: number;
|
||||
role: UserRole;
|
||||
}
|
||||
|
||||
export interface BackupFile {
|
||||
filename: string;
|
||||
size: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const FILENAME_RE = /^backup-[\w-]+\.zip$/;
|
||||
|
||||
/**
|
||||
* バックアップ作成・一覧・ダウンロードを担うService。
|
||||
* SQLite DBファイル + uploadsディレクトリをZIP化し、backups/ に保存する。
|
||||
* すべての操作は system_admin ロールに限定される。
|
||||
*/
|
||||
export class BackupService {
|
||||
constructor(
|
||||
private readonly dbPath: string,
|
||||
private readonly uploadsDir: string,
|
||||
private readonly backupsDir: string
|
||||
) {}
|
||||
|
||||
createBackup(actor: BackupActor): BackupFile {
|
||||
this.requireAdmin(actor);
|
||||
fs.mkdirSync(this.backupsDir, { recursive: true });
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const filename = `backup-${timestamp}.zip`;
|
||||
const files: Record<string, Uint8Array> = {};
|
||||
|
||||
// DBファイル
|
||||
if (fs.existsSync(this.dbPath)) {
|
||||
files['app.db'] = new Uint8Array(fs.readFileSync(this.dbPath));
|
||||
}
|
||||
// uploadsディレクトリ
|
||||
this.collectUploads(files, this.uploadsDir, 'uploads');
|
||||
|
||||
const zip = zipSync(files);
|
||||
const fullPath = path.join(this.backupsDir, filename);
|
||||
fs.writeFileSync(fullPath, zip);
|
||||
|
||||
const stat = fs.statSync(fullPath);
|
||||
return {
|
||||
filename,
|
||||
size: stat.size,
|
||||
createdAt: stat.mtime.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
listBackups(actor: BackupActor): BackupFile[] {
|
||||
this.requireAdmin(actor);
|
||||
if (!fs.existsSync(this.backupsDir)) return [];
|
||||
const entries = fs
|
||||
.readdirSync(this.backupsDir)
|
||||
.filter((f) => f.endsWith('.zip') && FILENAME_RE.test(f))
|
||||
.map((filename) => {
|
||||
const stat = fs.statSync(path.join(this.backupsDir, filename));
|
||||
return {
|
||||
filename,
|
||||
size: stat.size,
|
||||
createdAt: stat.mtime.toISOString(),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
|
||||
return entries;
|
||||
}
|
||||
|
||||
getBackupPath(actor: BackupActor, filename: string): string {
|
||||
this.requireAdmin(actor);
|
||||
if (!FILENAME_RE.test(filename)) {
|
||||
throw new NotFoundError('Backup', filename);
|
||||
}
|
||||
const fullPath = path.join(this.backupsDir, filename);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new NotFoundError('Backup', filename);
|
||||
}
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
private requireAdmin(actor: BackupActor): void {
|
||||
if (actor.role !== 'system_admin') {
|
||||
throw new ForbiddenError('管理者のみアクセス可能です');
|
||||
}
|
||||
}
|
||||
|
||||
private collectUploads(
|
||||
files: Record<string, Uint8Array>,
|
||||
dir: string,
|
||||
prefix: string
|
||||
): void {
|
||||
if (!fs.existsSync(dir)) return;
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
const fullPath = path.join(dir, entry);
|
||||
const rel = `${prefix}/${entry}`;
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
this.collectUploads(files, fullPath, rel);
|
||||
} else {
|
||||
files[rel] = new Uint8Array(fs.readFileSync(fullPath));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
61
tests/e2e/backup.spec.ts
Normal file
61
tests/e2e/backup.spec.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
async function login(page: Page, email: string, password: string) {
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('メールアドレス').fill(email);
|
||||
await page.getByLabel('パスワード').fill(password);
|
||||
await page.getByRole('button', { name: 'ログイン' }).click();
|
||||
await expect(page).toHaveURL(/\/dashboard/);
|
||||
}
|
||||
|
||||
test.describe('backup & admin', () => {
|
||||
test('admin creates, lists, and downloads a backup; non-admin is forbidden', async ({
|
||||
browser,
|
||||
request,
|
||||
}) => {
|
||||
// 管理者(globalSetup で seed 済み)でログイン
|
||||
const adminContext = await browser.newContext();
|
||||
const adminPage = await adminContext.newPage();
|
||||
await login(adminPage, 'admin@example.com', 'admin123');
|
||||
|
||||
// バックアップ一覧画面
|
||||
await adminPage.goto('/admin/backups');
|
||||
await expect(
|
||||
adminPage.getByRole('heading', { name: '管理者: バックアップ' })
|
||||
).toBeVisible();
|
||||
|
||||
// バックアップ作成(API)
|
||||
const createRes = await adminPage.request.post('/api/admin/backups');
|
||||
expect(createRes.ok()).toBeTruthy();
|
||||
const { backup } = (await createRes.json()) as {
|
||||
backup: { filename: string };
|
||||
};
|
||||
|
||||
// 一覧に表示
|
||||
await adminPage.reload();
|
||||
await expect(
|
||||
adminPage.getByTestId(`backup-${backup.filename}`)
|
||||
).toBeVisible();
|
||||
|
||||
// ダウンロード(API)
|
||||
const dlRes = await adminPage.request.get(
|
||||
`/api/admin/backups/${backup.filename}`
|
||||
);
|
||||
expect(dlRes.status()).toBe(200);
|
||||
expect(dlRes.headers()['content-type']).toContain('application/zip');
|
||||
|
||||
// 非管理者は403
|
||||
const memberEmail = `member-${Date.now()}@example.com`;
|
||||
await request.post('/api/auth/register', {
|
||||
data: { name: 'Member', email: memberEmail, password: 'password123' },
|
||||
});
|
||||
const memberContext = await browser.newContext();
|
||||
const memberPage = await memberContext.newPage();
|
||||
await login(memberPage, memberEmail, 'password123');
|
||||
const forbidden = await memberPage.request.get('/api/admin/backups');
|
||||
expect(forbidden.status()).toBe(403);
|
||||
|
||||
await adminContext.close();
|
||||
await memberContext.close();
|
||||
});
|
||||
});
|
||||
34
tests/e2e/globalSetup.ts
Normal file
34
tests/e2e/globalSetup.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { SqliteDatabase } from '@/lib/db/sqlite';
|
||||
import { Migrator } from '@/lib/db/migrator';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
|
||||
const ADMIN_EMAIL = 'admin@example.com';
|
||||
const ADMIN_PASSWORD = 'admin123';
|
||||
|
||||
/**
|
||||
* E2E用の初期データをセットアップする。
|
||||
* - Migrationを確実に適用(開発サーバのmigrateと重複しても冪等)
|
||||
* - バックアップ/管理者機能のE2Eで使用する system_admin ユーザーを生成
|
||||
*/
|
||||
export default async function globalSetup(): Promise<void> {
|
||||
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
|
||||
const db = new SqliteDatabase(dbPath);
|
||||
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
|
||||
new Migrator(db, migrationsDir).migrate();
|
||||
|
||||
const userRepo = new UserRepository(db);
|
||||
if (!userRepo.findByEmail(ADMIN_EMAIL)) {
|
||||
userRepo.create({
|
||||
name: 'Admin',
|
||||
email: ADMIN_EMAIL,
|
||||
passwordHash: bcrypt.hashSync(ADMIN_PASSWORD, 10),
|
||||
role: 'system_admin',
|
||||
});
|
||||
}
|
||||
db.close();
|
||||
}
|
||||
81
tests/unit/services/BackupService.test.ts
Normal file
81
tests/unit/services/BackupService.test.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { unzipSync } from 'fflate';
|
||||
import { BackupService } from '@/services/BackupService';
|
||||
import { ForbiddenError, NotFoundError } from '@/lib/errors';
|
||||
|
||||
describe('BackupService', () => {
|
||||
let root: string;
|
||||
let dbPath: string;
|
||||
let uploadsDir: string;
|
||||
let backupsDir: string;
|
||||
let service: BackupService;
|
||||
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'backup-'));
|
||||
dbPath = path.join(root, 'app.db');
|
||||
uploadsDir = path.join(root, 'uploads');
|
||||
backupsDir = path.join(root, 'backups');
|
||||
fs.writeFileSync(dbPath, Buffer.from('fake-db-content'));
|
||||
fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(uploadsDir, 'a.txt'), Buffer.from('hello'));
|
||||
fs.mkdirSync(path.join(uploadsDir, 'sub'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(uploadsDir, 'sub', 'b.txt'),
|
||||
Buffer.from('world')
|
||||
);
|
||||
service = new BackupService(dbPath, uploadsDir, backupsDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const admin = { id: 1, role: 'system_admin' as const };
|
||||
const member = { id: 2, role: 'member' as const };
|
||||
|
||||
it('createBackup zips DB + uploads into backups dir', () => {
|
||||
const backup = service.createBackup(admin);
|
||||
expect(backup.filename).toMatch(/^backup-.+\.zip$/);
|
||||
const fullPath = path.join(backupsDir, backup.filename);
|
||||
expect(fs.existsSync(fullPath)).toBe(true);
|
||||
expect(backup.size).toBeGreaterThan(0);
|
||||
|
||||
// ZIP内容を検証
|
||||
const zip = new Uint8Array(fs.readFileSync(fullPath));
|
||||
const unzipped = unzipSync(zip);
|
||||
expect(Object.keys(unzipped)).toContain('app.db');
|
||||
expect(Object.keys(unzipped)).toContain('uploads/a.txt');
|
||||
expect(Object.keys(unzipped)).toContain('uploads/sub/b.txt');
|
||||
});
|
||||
|
||||
it('listBackups returns created backups newest first', () => {
|
||||
service.createBackup(admin);
|
||||
const list = service.listBackups(admin);
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].filename).toMatch(/^backup-.+\.zip$/);
|
||||
});
|
||||
|
||||
it('forbids a non-admin from creating/listing', () => {
|
||||
expect(() => service.createBackup(member)).toThrow(ForbiddenError);
|
||||
expect(() => service.listBackups(member)).toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('getBackupPath rejects path traversal and missing files', () => {
|
||||
service.createBackup(admin);
|
||||
expect(() => service.getBackupPath(admin, '../evil.zip')).toThrow(
|
||||
NotFoundError
|
||||
);
|
||||
expect(() =>
|
||||
service.getBackupPath(admin, 'backup-doesnotexist.zip')
|
||||
).toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('getBackupPath returns the path for a valid backup', () => {
|
||||
const backup = service.createBackup(admin);
|
||||
const p = service.getBackupPath(admin, backup.filename);
|
||||
expect(fs.existsSync(p)).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user