diff --git a/components/admin/BackupCreateButton.tsx b/components/admin/BackupCreateButton.tsx new file mode 100644 index 0000000..d325bd3 --- /dev/null +++ b/components/admin/BackupCreateButton.tsx @@ -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(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 ( +
+

+ DBファイル + uploadsディレクトリをZIP化してバックアップを作成します。 +

+ + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/lib/api/services.ts b/lib/api/services.ts index 9e6489a..ba274ce 100644 --- a/lib/api/services.ts +++ b/lib/api/services.ts @@ -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()); } diff --git a/package-lock.json b/package-lock.json index d5cdd16..e4ba759 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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": { diff --git a/package.json b/package.json index 7c1c491..59e8551 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/playwright.config.ts b/playwright.config.ts index 37f4716..4addb17 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -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', diff --git a/services/BackupService.ts b/services/BackupService.ts new file mode 100644 index 0000000..879acaf --- /dev/null +++ b/services/BackupService.ts @@ -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 = {}; + + // 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, + 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)); + } + } + } +} diff --git a/tests/e2e/backup.spec.ts b/tests/e2e/backup.spec.ts new file mode 100644 index 0000000..482f909 --- /dev/null +++ b/tests/e2e/backup.spec.ts @@ -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(); + }); +}); diff --git a/tests/e2e/globalSetup.ts b/tests/e2e/globalSetup.ts new file mode 100644 index 0000000..4bac28c --- /dev/null +++ b/tests/e2e/globalSetup.ts @@ -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 { + 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(); +} diff --git a/tests/unit/services/BackupService.test.ts b/tests/unit/services/BackupService.test.ts new file mode 100644 index 0000000..d9b2be9 --- /dev/null +++ b/tests/unit/services/BackupService.test.ts @@ -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); + }); +});