32 lines
2.8 KiB
TypeScript
32 lines
2.8 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
import { randomBytes, timingSafeEqual } from 'crypto';
|
|
import { totp } from '../../../lib/totp';
|
|
import { query } from '../../../lib/db';
|
|
import { COOKIE, signSession } from '../../../lib/editor-session';
|
|
|
|
export default async function login(req: NextApiRequest, res: NextApiResponse) {
|
|
res.setHeader('Cache-Control', 'no-store');
|
|
if (req.method !== 'POST') return res.status(405).end();
|
|
if (!process.env.EDITOR_ORIGIN || req.headers.origin !== process.env.EDITOR_ORIGIN) return res.status(403).json({ error: 'Invalid origin' });
|
|
const { code } = req.body || {};
|
|
const secret = process.env.EDITOR_TOTP_SECRET;
|
|
if (!secret || !process.env.EDITOR_ORIGIN || (process.env.EDITOR_SESSION_SECRET?.length || 0) < 32) return res.status(503).json({ error: 'Editor access has not been configured on the server.' });
|
|
if (typeof code !== 'string' || !/^\d{6}$/.test(code)) return res.status(401).json({ error: 'Check your authenticator code.' });
|
|
try {
|
|
// A database-backed global limit works across processes; never trust spoofable forwarding headers.
|
|
await query(`CREATE SCHEMA IF NOT EXISTS analysis`);
|
|
await query(`CREATE TABLE IF NOT EXISTS analysis.editor_auth (id integer PRIMARY KEY, attempts integer NOT NULL, window_start timestamptz NOT NULL, last_step bigint NOT NULL DEFAULT -1)`);
|
|
await query(`INSERT INTO analysis.editor_auth (id, attempts, window_start) VALUES (1,0,now()) ON CONFLICT DO NOTHING`);
|
|
const limit = await query<{attempts:number}>(`UPDATE analysis.editor_auth SET attempts = CASE WHEN window_start < now() - interval '5 minutes' THEN 1 ELSE attempts + 1 END, window_start = CASE WHEN window_start < now() - interval '5 minutes' THEN now() ELSE window_start END WHERE id=1 RETURNING attempts`);
|
|
if (limit[0].attempts > 10) return res.status(429).json({ error: 'Too many attempts. Try again in five minutes.' });
|
|
const step = Math.floor(Date.now() / 30000);
|
|
const accepted = [step - 1, step, step + 1].find(s => timingSafeEqual(Buffer.from(totp(secret, s)), Buffer.from(code)));
|
|
if (accepted === undefined) return res.status(401).json({ error: 'Check your authenticator code.' });
|
|
const used = await query(`UPDATE analysis.editor_auth SET last_step=? WHERE id=1 AND last_step < ? RETURNING id`, [accepted, accepted]);
|
|
if (!used.length) return res.status(401).json({ error: 'Use a fresh authenticator code.' });
|
|
const value = `${Date.now() + 8 * 3600_000}.${randomBytes(16).toString('hex')}`;
|
|
res.setHeader('Set-Cookie', `${COOKIE}=${value}.${await signSession(value)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800${process.env.EDITOR_ORIGIN.startsWith('https://') ? '; Secure' : ''}`);
|
|
return res.json({ ok: true });
|
|
} catch { return res.status(503).json({ error: 'Authentication service unavailable.' }); }
|
|
}
|