Harden private media and backup recovery; add V2 deployment and migration guides
This commit is contained in:
parent
c549c34f60
commit
ffaa1f6afa
19 changed files with 623 additions and 14 deletions
|
|
@ -137,9 +137,17 @@ export function createApp(app: AppContext): Hono {
|
|||
if (!webDir) {
|
||||
return c.text('The web app has not been built. Run "npm run build", or use "npm run dev" and open the Vite dev server.', 404);
|
||||
}
|
||||
const urlPath = decodeURIComponent(new URL(c.req.url).pathname);
|
||||
let urlPath: string;
|
||||
try {
|
||||
urlPath = decodeURIComponent(new URL(c.req.url).pathname);
|
||||
} catch {
|
||||
return c.text('Invalid URL', 400);
|
||||
}
|
||||
const candidate = path.normalize(path.join(webDir, urlPath));
|
||||
if (candidate.startsWith(webDir) && urlPath !== '/' && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
||||
const relative = path.relative(webDir, candidate);
|
||||
const inside = relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
||||
if (!inside) return c.text('Not found', 404);
|
||||
if (urlPath !== '/' && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
||||
// Hashed build assets never change; everything else is revalidated.
|
||||
const immutable = urlPath.startsWith('/assets/');
|
||||
return sendFile(candidate, immutable ? 'public, max-age=31536000, immutable' : 'no-cache');
|
||||
|
|
|
|||
|
|
@ -31,16 +31,21 @@ function bool(v: string | undefined, fallback: boolean): boolean {
|
|||
}
|
||||
|
||||
function loadSecret(dataDir: string, fromEnv: string | undefined): Buffer {
|
||||
if (fromEnv && fromEnv.trim().length >= 16) {
|
||||
if (fromEnv && fromEnv.trim().length < 16) throw new Error('APP_SECRET must contain at least 16 characters.');
|
||||
if (fromEnv) {
|
||||
return crypto.createHash('sha256').update(`studydesk:${fromEnv.trim()}`).digest();
|
||||
}
|
||||
const file = path.join(dataDir, 'secret.key');
|
||||
if (fs.existsSync(file)) {
|
||||
const raw = Buffer.from(fs.readFileSync(file, 'utf8').trim(), 'base64');
|
||||
if (raw.length === 32) return raw;
|
||||
throw new Error('secret.key is damaged. Restore the original key from your backup; refusing to replace it.');
|
||||
}
|
||||
if (fs.existsSync(path.join(dataDir, 'study.db'))) {
|
||||
throw new Error('Existing database has no secret.key. Restore its original key or set the original APP_SECRET; refusing to generate a replacement.');
|
||||
}
|
||||
const key = crypto.randomBytes(32);
|
||||
fs.writeFileSync(file, key.toString('base64'), { mode: 0o600 });
|
||||
fs.writeFileSync(file, key.toString('base64'), { mode: 0o600, flag: 'wx' });
|
||||
return key;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Hono } from 'hono';
|
|||
import { bodyLimit } from 'hono/body-limit';
|
||||
import { z } from 'zod';
|
||||
import { titleSchema } from '../../shared/content.ts';
|
||||
import { isAuthenticated } from '../auth.ts';
|
||||
import { badRequest, HttpError, idParam, readBody, type AppContext } from '../http.ts';
|
||||
import { getClass, mapClass, resolveFolder } from '../services/content.ts';
|
||||
import { deleteDocument, documentPath, enqueue, getDocument, ingestUpload, listChunks, mapDocument, sourceLabel } from '../services/documents.ts';
|
||||
|
|
@ -162,19 +163,35 @@ export function documentRoutes(app: AppContext): Hono {
|
|||
}
|
||||
|
||||
/**
|
||||
* Public image route. Images are addressed by an unguessable 128-bit name, which is what lets
|
||||
* a shared quiz show its pictures to visitors without exposing anything else.
|
||||
* Images are private unless an enabled share contains a reference to them.
|
||||
* Re-check on each request so revoking a share also revokes its embedded images.
|
||||
*/
|
||||
export function mediaRoute(app: AppContext): Hono {
|
||||
const r = new Hono();
|
||||
r.get('/:name', (c) => {
|
||||
const name = c.req.param('name');
|
||||
if (!/^[A-Za-z0-9_-]{16,40}\.(png|jpg|gif|webp)$/.test(name)) throw new HttpError(404, 'not_found', 'Not found');
|
||||
if (!isAuthenticated(app, c)) {
|
||||
const reference = `/media/${name}`;
|
||||
const shared = app.db.get(`
|
||||
SELECT 1 FROM shares s WHERE s.enabled = 1 AND (
|
||||
EXISTS (SELECT 1 FROM questions q JOIN quizzes z ON z.id = q.quiz_id
|
||||
WHERE ((s.kind = 'quiz' AND s.target_id = z.id) OR (s.kind = 'class' AND s.target_id = z.class_id) OR (s.kind = 'folder' AND s.target_id = z.folder_id))
|
||||
AND instr(q.stem || q.options || q.rationale, ?) > 0)
|
||||
OR EXISTS (SELECT 1 FROM cards c JOIN decks d ON d.id = c.deck_id
|
||||
WHERE ((s.kind = 'deck' AND s.target_id = d.id) OR (s.kind = 'class' AND s.target_id = d.class_id) OR (s.kind = 'folder' AND s.target_id = d.folder_id))
|
||||
AND instr(c.front || c.back || c.hint, ?) > 0)
|
||||
OR EXISTS (SELECT 1 FROM notes n
|
||||
WHERE ((s.kind = 'note' AND s.target_id = n.id) OR (s.kind = 'class' AND s.target_id = n.class_id) OR (s.kind = 'folder' AND s.target_id = n.folder_id))
|
||||
AND instr(n.content, ?) > 0)
|
||||
) LIMIT 1`, reference, reference, reference);
|
||||
if (!shared) throw new HttpError(404, 'not_found', 'Not found');
|
||||
}
|
||||
const row = app.db.get<{ mime: string }>('SELECT mime FROM media WHERE id = ?', name);
|
||||
const file = path.join(app.config.mediaDir, name);
|
||||
if (!row || !fs.existsSync(file)) throw new HttpError(404, 'not_found', 'Not found');
|
||||
return new Response(fs.readFileSync(file), {
|
||||
headers: { 'Content-Type': row.mime, 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; sandbox" },
|
||||
headers: { 'Content-Type': row.mime, 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; sandbox" },
|
||||
});
|
||||
});
|
||||
return r;
|
||||
|
|
|
|||
|
|
@ -89,6 +89,10 @@ export function fullBackupStream(app: AppContext): { stream: ReadableStream<Uint
|
|||
const tmp = path.join(app.config.backupsDir, `.export-${Date.now()}.db`);
|
||||
app.db.snapshot(tmp);
|
||||
const entries: { name: string; file: string }[] = [{ name: 'study.db', file: tmp }];
|
||||
// Include the generated key so a full backup can actually restore encrypted AI settings.
|
||||
// APP_SECRET is deliberately never exported; deployments using it must retain it separately.
|
||||
const keyFile = path.join(app.config.dataDir, 'secret.key');
|
||||
if (fs.existsSync(keyFile)) entries.push({ name: 'secret.key', file: keyFile });
|
||||
for (const [dir, prefix] of [
|
||||
[app.config.uploadsDir, 'uploads'],
|
||||
[app.config.mediaDir, 'media'],
|
||||
|
|
@ -104,7 +108,7 @@ export function fullBackupStream(app: AppContext): { stream: ReadableStream<Uint
|
|||
version: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
files: entries.length,
|
||||
restore: 'Stop the container, copy study.db, uploads/ and media/ into the data folder (replacing what is there), keep your existing secret.key, then start the container.',
|
||||
restore: 'Stop the container. Restore into a NEW data folder: study.db, uploads/, media/ and secret.key if present. Preserve the original APP_SECRET separately if configured. Never retain old study.db-wal or study.db-shm files. Keep the old folder intact until the restored installation is verified.',
|
||||
};
|
||||
let index = -1;
|
||||
let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;
|
||||
|
|
@ -139,11 +143,14 @@ export function fullBackupStream(app: AppContext): { stream: ReadableStream<Uint
|
|||
zip.add(entry);
|
||||
try {
|
||||
entry.push(new Uint8Array(fs.readFileSync(file)), true);
|
||||
} catch {
|
||||
entry.push(new Uint8Array(0), true);
|
||||
} catch (error) {
|
||||
controllerRef?.error(error);
|
||||
zip.terminate();
|
||||
cleanup();
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
zip.terminate();
|
||||
cleanup();
|
||||
},
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue