import fs from 'node:fs'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import { strToU8, unzipSync, zipSync } from 'fflate'; import { afterEach, describe, expect, it } from 'vitest'; import { decryptSecret, encryptSecret } from '../server/crypto.ts'; import { getSetting, setSetting } from '../server/settings.ts'; import { createTestApp, type TestApp } from './helpers.ts'; const apps: TestApp[] = []; async function newApp(): Promise { const app = await createTestApp(); apps.push(app); return app; } afterEach(() => { for (const app of apps.splice(0)) { try { app.ctx.db.close(); } catch { /* already closed */ } fs.rmSync(app.dir, { recursive: true, force: true }); } }); async function backupOf(app: TestApp): Promise { const res = await app.raw('GET', '/api/backup/download'); expect(res.status).toBe(200); return new Uint8Array(await res.arrayBuffer()); } const restore = (app: TestApp, zip: Uint8Array) => app.raw('POST', '/api/backup/restore', { headers: { 'content-type': 'application/zip' }, body: zip }); describe('restoring a full backup', () => { it('replaces the data, settings and files, moves saved keys to this server and keeps the session', async () => { const source = await newApp(); await source.api('POST', '/api/classes', { name: 'Backed up class' }); setSetting(source.ctx.db, 'test.sealed', { apiKey: encryptSecret('test-only-key', source.ctx.config.secretKey) }); setSetting(source.ctx.db, 'test.plain', 'kept'); fs.writeFileSync(path.join(source.ctx.config.uploadsDir, 'lecture.txt'), 'Uploaded lecture'); const zip = await backupOf(source); const target = await newApp(); await target.api('POST', '/api/classes', { name: 'Replaced class' }); fs.writeFileSync(path.join(target.ctx.config.uploadsDir, 'local-only.txt'), 'Left alone'); // Two installs have different keys, so the sealed key must be re-encrypted to be readable. expect(target.ctx.config.secretKey.equals(source.ctx.config.secretKey)).toBe(false); const res = await restore(target, zip); const body = (await res.json()) as { summary: Record }; expect(res.status).toBe(200); expect(body.summary).toMatchObject({ classes: 1, files: 1, keysMoved: 1, keysUnreadable: 0 }); expect(String(body.summary.safetySnapshot)).toMatch(/^pre-restore-/); // Still signed in, now looking at the restored library. const classes = await target.api('GET', '/api/classes'); expect(classes.status).toBe(200); expect(classes.body.classes.map((c: { name: string }) => c.name)).toEqual(['Backed up class']); expect(getSetting(target.ctx.db, 'test.plain', '')).toBe('kept'); const sealed = getSetting<{ apiKey: string }>(target.ctx.db, 'test.sealed', { apiKey: '' }).apiKey; expect(decryptSecret(sealed, target.ctx.config.secretKey)).toBe('test-only-key'); expect(fs.readFileSync(path.join(target.ctx.config.uploadsDir, 'lecture.txt'), 'utf8')).toBe('Uploaded lecture'); expect(fs.existsSync(path.join(target.ctx.config.uploadsDir, 'local-only.txt'))).toBe(true); // The database as it was before is kept as a snapshot, and no staging files are left. const before = new DatabaseSync(path.join(target.ctx.config.backupsDir, String(body.summary.safetySnapshot)), { readOnly: true }); expect((before.prepare('SELECT name FROM classes').all() as { name: string }[]).map((r) => r.name)).toEqual(['Replaced class']); before.close(); expect(fs.readdirSync(target.ctx.config.dataDir).filter((f) => f.startsWith('.restore'))).toEqual([]); // The swapped handle keeps working for writes. expect((await target.api('POST', '/api/classes', { name: 'After restore' })).status).toBe(201); }); it('refuses files that are not a usable backup and leaves the data untouched', async () => { const app = await newApp(); await app.api('POST', '/api/classes', { name: 'Untouched' }); const notZip = await restore(app, strToU8('just some text, not a zip file at all')); expect(notZip.status).toBe(400); const noDb = await restore(app, zipSync({ 'notes.txt': strToU8('hello') })); expect(noDb.status).toBe(400); expect(((await noDb.json()) as { error: { message: string } }).error.message).toMatch(/no study\.db/); // A backup from a newer version (a migration this server does not know) is refused. const files = unzipSync(await backupOf(app)); const tmp = path.join(app.dir, 'newer.db'); fs.writeFileSync(tmp, files['study.db']!); const newer = new DatabaseSync(tmp); newer.prepare('INSERT INTO schema_migrations (id, name, applied_at) VALUES (999999, ?, ?)').run('from_the_future', Date.now()); newer.close(); files['study.db'] = new Uint8Array(fs.readFileSync(tmp)); const future = await restore(app, zipSync(files)); expect(future.status).toBe(400); expect(((await future.json()) as { error: { message: string } }).error.message).toMatch(/newer version/); const classes = await app.api('GET', '/api/classes'); expect(classes.body.classes.map((c: { name: string }) => c.name)).toEqual(['Untouched']); }); });