Start Study Desk V2: remove V1 sources, add backend foundation
V1 remains intact on main and in history. This branch replaces it with a new application: node:sqlite storage with migrations, scrypt auth and sessions, content/SRS/attempt/stats services, document extraction and chunking, a provider-neutral AI layer (OpenAI, Anthropic, Gemini, OpenAI-compatible, Ollama), the generation pipeline and the tool-using assistant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
7bd0a9aad4
commit
3e74ecd843
268 changed files with 17740 additions and 55423 deletions
277
server/auth.ts
Normal file
277
server/auth.ts
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { Hono, type Context, type MiddlewareHandler } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import { z } from 'zod';
|
||||
import { hashPassword, safeEqual, verifyPassword } from './crypto.ts';
|
||||
import { HttpError, readBody, type AppContext } from './http.ts';
|
||||
import { deleteSetting, getSetting, setSetting } from './settings.ts';
|
||||
import { newToken, now, sha256 } from './util.ts';
|
||||
|
||||
const COOKIE = 'sd_session';
|
||||
const SESSION_MS = 30 * 86_400_000;
|
||||
const PASSWORD_MIN = 8;
|
||||
|
||||
const passwordSchema = z.string().min(PASSWORD_MIN, `Use at least ${PASSWORD_MIN} characters`).max(256);
|
||||
|
||||
/* ------------------------------ rate limiting ------------------------------ */
|
||||
|
||||
interface Bucket {
|
||||
failures: number[];
|
||||
}
|
||||
const WINDOW_MS = 15 * 60_000;
|
||||
const MAX_PER_IP = 8;
|
||||
const MAX_GLOBAL = 40;
|
||||
const buckets = new Map<string, Bucket>();
|
||||
|
||||
function recent(key: string, at: number): number[] {
|
||||
const bucket = buckets.get(key) ?? { failures: [] };
|
||||
bucket.failures = bucket.failures.filter((t) => at - t < WINDOW_MS);
|
||||
buckets.set(key, bucket);
|
||||
return bucket.failures;
|
||||
}
|
||||
|
||||
function assertNotLimited(ip: string): void {
|
||||
const at = now();
|
||||
const mine = recent(`ip:${ip}`, at);
|
||||
const all = recent('global', at);
|
||||
if (mine.length >= MAX_PER_IP || all.length >= MAX_GLOBAL) {
|
||||
const oldest = (mine.length >= MAX_PER_IP ? mine : all)[0];
|
||||
const retry = Math.max(1, Math.ceil((oldest + WINDOW_MS - at) / 1000));
|
||||
throw new HttpError(429, 'rate_limited', `Too many attempts. Try again in ${Math.ceil(retry / 60)} minute${retry > 60 ? 's' : ''}.`, { retryAfter: retry });
|
||||
}
|
||||
}
|
||||
|
||||
function recordFailure(ip: string): void {
|
||||
const at = now();
|
||||
recent(`ip:${ip}`, at).push(at);
|
||||
recent('global', at).push(at);
|
||||
}
|
||||
|
||||
export function resetRateLimits(): void {
|
||||
buckets.clear();
|
||||
}
|
||||
|
||||
/* ------------------------------ request helpers ------------------------------ */
|
||||
|
||||
export function clientIp(c: Context, trustProxy: boolean): string {
|
||||
if (trustProxy) {
|
||||
const fwd = c.req.header('x-forwarded-for');
|
||||
if (fwd) return fwd.split(',')[0].trim();
|
||||
const real = c.req.header('x-real-ip');
|
||||
if (real) return real.trim();
|
||||
}
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? 'unknown';
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
export function isHttps(c: Context, trustProxy: boolean): boolean {
|
||||
if (trustProxy) {
|
||||
const proto = c.req.header('x-forwarded-proto');
|
||||
if (proto) return proto.split(',')[0].trim() === 'https';
|
||||
}
|
||||
return new URL(c.req.url).protocol === 'https:';
|
||||
}
|
||||
|
||||
/* ------------------------------ sessions ------------------------------ */
|
||||
|
||||
function createSession(app: AppContext, c: Context): void {
|
||||
const token = newToken();
|
||||
const at = now();
|
||||
app.db.run(
|
||||
'INSERT INTO sessions (token_hash, created_at, expires_at, last_seen_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
sha256(token),
|
||||
at,
|
||||
at + SESSION_MS,
|
||||
at,
|
||||
(c.req.header('user-agent') ?? '').slice(0, 300),
|
||||
clientIp(c, app.config.trustProxy),
|
||||
);
|
||||
app.db.run('DELETE FROM sessions WHERE expires_at < ?', at);
|
||||
const secure = app.config.cookieSecure === 'auto' ? isHttps(c, app.config.trustProxy) : app.config.cookieSecure;
|
||||
setCookie(c, COOKIE, token, { httpOnly: true, sameSite: 'Lax', secure, path: '/', maxAge: Math.floor(SESSION_MS / 1000) });
|
||||
}
|
||||
|
||||
export function isAuthenticated(app: AppContext, c: Context): boolean {
|
||||
const token = getCookie(c, COOKIE);
|
||||
if (!token) return false;
|
||||
const hash = sha256(token);
|
||||
const at = now();
|
||||
const row = app.db.get<{ expires_at: number; last_seen_at: number }>('SELECT expires_at, last_seen_at FROM sessions WHERE token_hash = ?', hash);
|
||||
if (!row || row.expires_at < at) return false;
|
||||
// Sliding expiry, written at most once an hour.
|
||||
if (at - row.last_seen_at > 3_600_000) {
|
||||
app.db.run('UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE token_hash = ?', at, at + SESSION_MS, hash);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function requireAuth(app: AppContext): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
if (!isAuthenticated(app, c)) throw new HttpError(401, 'unauthorized', 'Sign in to continue');
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* CSRF defence for cookie-authenticated requests: state-changing calls must carry a custom
|
||||
* header (which a cross-site form cannot send, and which forces a CORS preflight that this
|
||||
* server never approves), and must not be flagged cross-site by the browser.
|
||||
*/
|
||||
export function csrfGuard(): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
const method = c.req.method;
|
||||
if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {
|
||||
if (c.req.header('x-requested-with') !== 'studydesk') throw new HttpError(403, 'csrf', 'Missing request header');
|
||||
// Fetch metadata is set by the browser and cannot be forged by page script. Using it
|
||||
// (rather than comparing Origin to Host) keeps this working behind proxies that rewrite Host.
|
||||
if (c.req.header('sec-fetch-site') === 'cross-site') throw new HttpError(403, 'csrf', 'Cross-site request blocked');
|
||||
}
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------ password storage ------------------------------ */
|
||||
|
||||
const HASH_KEY = 'auth.password_hash';
|
||||
const SETUP_KEY = 'auth.setup_code';
|
||||
|
||||
export function isConfigured(app: AppContext): boolean {
|
||||
return Boolean(getSetting<string | null>(app.db, HASH_KEY, null));
|
||||
}
|
||||
|
||||
function setupCodeFile(app: AppContext): string {
|
||||
return path.join(app.config.dataDir, 'setup-code.txt');
|
||||
}
|
||||
|
||||
async function storePassword(app: AppContext, password: string): Promise<void> {
|
||||
setSetting(app.db, HASH_KEY, await hashPassword(password));
|
||||
deleteSetting(app.db, SETUP_KEY);
|
||||
fs.rmSync(setupCodeFile(app), { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs at startup. Applies ADMIN_PASSWORD / RESET_ADMIN_PASSWORD, or prepares a one-time
|
||||
* setup code (printed to the log and written to the data folder) so that only someone with
|
||||
* access to the server can claim a fresh install.
|
||||
*/
|
||||
export async function initAuth(app: AppContext): Promise<void> {
|
||||
const { config, db } = app;
|
||||
if (config.resetAdminPassword) {
|
||||
passwordSchema.parse(config.resetAdminPassword);
|
||||
await storePassword(app, config.resetAdminPassword);
|
||||
db.run('DELETE FROM sessions');
|
||||
app.log('warn', 'Administrator password was reset from RESET_ADMIN_PASSWORD. Remove that variable and restart.');
|
||||
return;
|
||||
}
|
||||
if (isConfigured(app)) return;
|
||||
if (config.adminPassword) {
|
||||
passwordSchema.parse(config.adminPassword);
|
||||
await storePassword(app, config.adminPassword);
|
||||
app.log('info', 'Administrator password initialised from ADMIN_PASSWORD.');
|
||||
return;
|
||||
}
|
||||
let code = getSetting<string | null>(db, SETUP_KEY, null);
|
||||
if (!code) {
|
||||
code = crypto.randomBytes(5).toString('hex').toUpperCase().replace(/(.{5})/, '$1-');
|
||||
setSetting(db, SETUP_KEY, code);
|
||||
}
|
||||
try {
|
||||
fs.writeFileSync(setupCodeFile(app), `${code}\n`, { mode: 0o600 });
|
||||
} catch {
|
||||
/* the log line below is enough */
|
||||
}
|
||||
app.log('info', `First-run setup code: ${code} (also saved to ${setupCodeFile(app)})`);
|
||||
}
|
||||
|
||||
/* ------------------------------ routes ------------------------------ */
|
||||
|
||||
export function authRoutes(app: AppContext): Hono {
|
||||
const r = new Hono();
|
||||
|
||||
r.get('/status', (c) => c.json({ configured: isConfigured(app), authenticated: isAuthenticated(app, c) }));
|
||||
|
||||
r.post('/setup', async (c) => {
|
||||
if (isConfigured(app)) throw new HttpError(409, 'already_configured', 'Study Desk is already set up');
|
||||
const ip = clientIp(c, app.config.trustProxy);
|
||||
assertNotLimited(ip);
|
||||
const body = await readBody(c, z.object({ code: z.string().max(40), password: passwordSchema }));
|
||||
const expected = getSetting<string | null>(app.db, SETUP_KEY, null);
|
||||
const given = body.code.trim().toUpperCase();
|
||||
if (!expected || !(safeEqual(given, expected) || safeEqual(given, expected.replace('-', '')))) {
|
||||
recordFailure(ip);
|
||||
throw new HttpError(403, 'bad_setup_code', 'That setup code is not correct. Check the server log or setup-code.txt in the data folder.');
|
||||
}
|
||||
await storePassword(app, body.password);
|
||||
createSession(app, c);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
r.post('/login', async (c) => {
|
||||
const ip = clientIp(c, app.config.trustProxy);
|
||||
assertNotLimited(ip);
|
||||
const body = await readBody(c, z.object({ password: z.string().max(256) }));
|
||||
const hash = getSetting<string | null>(app.db, HASH_KEY, null);
|
||||
if (!hash) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet');
|
||||
if (!(await verifyPassword(body.password, hash))) {
|
||||
recordFailure(ip);
|
||||
throw new HttpError(401, 'bad_password', 'Incorrect password');
|
||||
}
|
||||
createSession(app, c);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
r.post('/logout', (c) => {
|
||||
const token = getCookie(c, COOKIE);
|
||||
if (token) app.db.run('DELETE FROM sessions WHERE token_hash = ?', sha256(token));
|
||||
deleteCookie(c, COOKIE, { path: '/' });
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
r.post('/password', requireAuth(app), async (c) => {
|
||||
const ip = clientIp(c, app.config.trustProxy);
|
||||
assertNotLimited(ip);
|
||||
const body = await readBody(c, z.object({ current: z.string().max(256), next: passwordSchema }));
|
||||
const hash = getSetting<string | null>(app.db, HASH_KEY, null);
|
||||
if (!hash || !(await verifyPassword(body.current, hash))) {
|
||||
recordFailure(ip);
|
||||
throw new HttpError(403, 'bad_password', 'Current password is incorrect');
|
||||
}
|
||||
await storePassword(app, body.next);
|
||||
// Sign out every other device.
|
||||
const token = getCookie(c, COOKIE);
|
||||
app.db.run('DELETE FROM sessions WHERE token_hash != ?', token ? sha256(token) : '');
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
r.get('/sessions', requireAuth(app), (c) => {
|
||||
const current = sha256(getCookie(c, COOKIE) ?? '');
|
||||
const rows = app.db.all<{ token_hash: string; created_at: number; last_seen_at: number; user_agent: string; ip: string }>(
|
||||
'SELECT token_hash, created_at, last_seen_at, user_agent, ip FROM sessions WHERE expires_at > ? ORDER BY last_seen_at DESC',
|
||||
now(),
|
||||
);
|
||||
return c.json({
|
||||
sessions: rows.map((s) => ({
|
||||
id: s.token_hash.slice(0, 12),
|
||||
createdAt: s.created_at,
|
||||
lastSeenAt: s.last_seen_at,
|
||||
userAgent: s.user_agent,
|
||||
ip: s.ip,
|
||||
current: s.token_hash === current,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
r.post('/sessions/revoke-others', requireAuth(app), (c) => {
|
||||
const current = sha256(getCookie(c, COOKIE) ?? '');
|
||||
const { changes } = app.db.run('DELETE FROM sessions WHERE token_hash != ?', current);
|
||||
return c.json({ revoked: changes });
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue