Harden private media and backup recovery; add V2 deployment and migration guides

This commit is contained in:
Elijah 2026-11-11 19:31:32 -07:00
parent c549c34f60
commit ffaa1f6afa
19 changed files with 623 additions and 14 deletions

91
tests/hardening.test.ts Normal file
View file

@ -0,0 +1,91 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { unzipSync } from 'fflate';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../server/config.ts';
import { encryptSecret, decryptSecret } from '../server/crypto.ts';
import { openDatabase } from '../server/db.ts';
import { TINY_PNG } from '../server/documents/testFixtures.ts';
import { createTestApp, type TestApp } from './helpers.ts';
let app: TestApp | undefined;
const dirs: string[] = [];
afterEach(() => {
app?.close();
app = undefined;
for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
const temporary = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-hardening-test-'));
dirs.push(dir);
return dir;
};
describe('private image authorization', () => {
it('only exposes an embedded image while its content has an enabled share', async () => {
app = await createTestApp();
const form = new FormData();
form.set('file', new File([Buffer.from(TINY_PNG)], 'private.png', { type: 'image/png' }));
const uploaded = await app.raw('POST', '/api/media', { body: form });
expect(uploaded.status).toBe(201);
const { url } = await uploaded.json() as { url: string };
expect((await app.raw('GET', url)).status).toBe(200);
expect((await app.raw('GET', url, { cookie: null })).status).toBe(404);
const cls = (await app.api('POST', '/api/classes', { name: 'Images' })).body.class;
const deck = (await app.api('POST', '/api/decks', { classId: cls.id, title: 'Picture deck', cards: [{ front: `![picture](${url})`, back: 'Answer' }] })).body.deck;
const share = (await app.api('POST', '/api/shares', { kind: 'deck', targetId: deck.id })).body.share;
const publicImage = await app.raw('GET', url, { cookie: null });
expect(publicImage.status).toBe(200);
expect(publicImage.headers.get('cache-control')).toContain('no-store');
await app.api('DELETE', `/api/shares/${share.id}`);
expect((await app.raw('GET', url, { cookie: null })).status).toBe(404);
const collection = (await app.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share;
expect((await app.raw('GET', url, { cookie: null })).status).toBe(200);
await app.api('PATCH', `/api/shares/${collection.id}`, { enabled: false });
expect((await app.raw('GET', url, { cookie: null })).status).toBe(404);
});
});
describe('key durability and restore', () => {
it('refuses a damaged encryption key without replacing it', () => {
const dir = temporary();
const config = loadConfig({ dataDir: dir }, {});
expect(loadConfig({ dataDir: dir }, {}).secretKey).toEqual(config.secretKey);
fs.writeFileSync(path.join(dir, 'secret.key'), 'damaged');
expect(() => loadConfig({ dataDir: dir }, {})).toThrow(/damaged/);
expect(fs.readFileSync(path.join(dir, 'secret.key'), 'utf8')).toBe('damaged');
expect(() => loadConfig({ dataDir: dir }, { APP_SECRET: 'short' })).toThrow(/16 characters/);
fs.unlinkSync(path.join(dir, 'secret.key'));
fs.writeFileSync(path.join(dir, 'study.db'), 'fixture');
expect(() => loadConfig({ dataDir: dir }, {})).toThrow(/no secret.key/);
});
it('restores a full backup into a new folder with data and the original encryption key', async () => {
app = await createTestApp();
await app.api('POST', '/api/classes', { name: 'Restored class' });
const encrypted = encryptSecret('test-only-provider-secret', app.ctx.config.secretKey);
fs.writeFileSync(path.join(app.ctx.config.uploadsDir, 'fixture.txt'), 'Preserved document');
const res = await app.raw('GET', '/api/backup/download');
const files = unzipSync(new Uint8Array(await res.arrayBuffer()));
expect(Object.keys(files)).toEqual(expect.arrayContaining(['study.db', 'secret.key', 'uploads/fixture.txt', 'manifest.json']));
const dir = temporary();
for (const [name, bytes] of Object.entries(files)) {
const file = path.join(dir, name);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, bytes);
}
const config = loadConfig({ dataDir: dir }, {});
expect(decryptSecret(encrypted, config.secretKey)).toBe('test-only-provider-secret');
const { db, report } = openDatabase(config.dbPath, config.backupsDir);
try {
expect(report.applied).toEqual([]);
expect(db.get<{ name: string }>('SELECT name FROM classes')?.name).toBe('Restored class');
expect(Object.values(db.get('PRAGMA integrity_check') ?? {})).toEqual(['ok']);
expect(db.all('PRAGMA foreign_key_check')).toEqual([]);
expect(fs.readFileSync(path.join(config.uploadsDir, 'fixture.txt'), 'utf8')).toBe('Preserved document');
} finally {
db.close();
}
});
});

79
tests/migration.test.ts Normal file
View file

@ -0,0 +1,79 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { describe, expect, it } from 'vitest';
import { DB, migrate } from '../server/db.ts';
import { MIGRATIONS } from '../server/migrations.ts';
import { importV1 } from '../server/services/v1import.ts';
import { createTestApp } from './helpers.ts';
describe('safe migration paths', () => {
it('previews and imports a V1 database without changing its bytes, preserving answers and schedules', async () => {
const app = await createTestApp();
const file = path.join(app.dir, 'v1-fixture.db');
const old = new DatabaseSync(file);
old.exec(`
CREATE TABLE Class (id TEXT, name TEXT, sortOrder INTEGER, createdAt INTEGER);
CREATE TABLE MaterialGroup (id TEXT, classId TEXT, name TEXT, sortOrder INTEGER, createdAt INTEGER);
CREATE TABLE Deck (id TEXT, classId TEXT, groupId TEXT, name TEXT, description TEXT, sortOrder INTEGER, createdAt INTEGER);
CREATE TABLE Flashcard (id TEXT, deckId TEXT, front TEXT, back TEXT, sortOrder INTEGER);
CREATE TABLE QuizSet (id TEXT, classId TEXT, groupId TEXT, name TEXT, description TEXT, sortOrder INTEGER, createdAt INTEGER);
CREATE TABLE Question (id TEXT, quizSetId TEXT, type TEXT, prompt TEXT, rationale TEXT, category TEXT, sortOrder INTEGER);
CREATE TABLE AnswerOption (id TEXT, questionId TEXT, text TEXT, isCorrect INTEGER, sortOrder INTEGER);
CREATE TABLE QuizAttempt (id TEXT, quizSetId TEXT, score REAL, maxScore INTEGER, answersJson TEXT, isPartialRetake INTEGER, completedAt INTEGER);
CREATE TABLE SpacedRepetitionCardState (flashcardId TEXT, state INTEGER, reps INTEGER, due INTEGER, stability REAL, difficulty REAL, scheduledDays INTEGER, learningSteps INTEGER, lapses INTEGER, lastReview INTEGER, firstReviewedAt INTEGER);
INSERT INTO Class VALUES ('c','Legacy class',0,1700000000000);
INSERT INTO MaterialGroup VALUES ('g','c','Legacy group',0,1700000000000);
INSERT INTO Deck VALUES ('d','c','g','Legacy deck','',0,1700000000000);
INSERT INTO Flashcard VALUES ('f','d','Term','Definition',0);
INSERT INTO QuizSet VALUES ('z','c','g','Legacy quiz','',0,1700000000000);
INSERT INTO Question VALUES ('q','z','MULTIPLE_CHOICE','Pick A','Reason','Topic',0);
INSERT INTO AnswerOption VALUES ('a','q','A',1,0),('b','q','B',0,1);
INSERT INTO QuizAttempt VALUES ('attempt','z',1,1,'{"q":["a"]}',0,1700000000000);
INSERT INTO SpacedRepetitionCardState VALUES ('f',2,7,1800000000000,15,5,14,0,1,1700000000000,1600000000000);
`);
old.close();
const digest = () => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
const before = digest();
try {
expect(importV1(app.ctx, file, { dryRun: true })).toMatchObject({ classes: 1, quizzes: 1, cards: 1, attempts: 1 });
expect(app.ctx.db.get<{ n: number }>('SELECT count(*) AS n FROM classes')?.n).toBe(0);
importV1(app.ctx, file);
expect(digest()).toBe(before);
const classes = (await app.api('GET', '/api/classes')).body.classes;
expect(classes[0].name).toBe('Legacy class');
const card = app.ctx.db.get<{ reps: number; due: number }>('SELECT reps, due FROM cards');
expect(card).toMatchObject({ reps: 7, due: 1800000000000 });
const attempt = app.ctx.db.get<{ id: string }>('SELECT id FROM attempts')!;
const result = (await app.api('GET', `/api/attempts/${attempt.id}`)).body;
expect(JSON.stringify(result)).toContain('Pick A');
expect(app.ctx.db.get<{ score: number }>('SELECT score FROM responses')?.score).toBe(1);
expect(app.ctx.db.all('PRAGMA foreign_key_check')).toEqual([]);
} finally {
app.close();
}
});
it('backs up before a schema change and rolls back a failed migration', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-migration-test-'));
const db = new DB(path.join(dir, 'test.db'));
try {
migrate(db, dir);
db.run("INSERT INTO settings VALUES ('fixture', 'preserved')");
MIGRATIONS.push({ id: 999999, name: 'test_failure', sql: 'CREATE TABLE should_rollback (id INTEGER); INVALID SQL;' });
try {
expect(() => migrate(db, dir)).toThrow();
expect(db.get("SELECT name FROM sqlite_master WHERE name = 'should_rollback'")).toBeUndefined();
expect(db.get<{ value: string }>("SELECT value FROM settings WHERE key = 'fixture'")?.value).toBe('preserved');
expect(fs.readdirSync(dir).some((n) => n.startsWith('pre-migration-'))).toBe(true);
} finally {
MIGRATIONS.pop();
}
} finally {
db.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
});