diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 796f2b8..91bd4ba 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -40,5 +40,8 @@ jobs: if: steps.checkout.outputs.skip != '1' env: APP_PORT: ${{ vars.APP_PORT }} + EDITOR_TOTP_SECRET: ${{ secrets.EDITOR_TOTP_SECRET }} + EDITOR_SESSION_SECRET: ${{ secrets.EDITOR_SESSION_SECRET }} + EDITOR_ORIGIN: http://8.211.154.134:18231 REFRESH_DATA: ${{ github.event_name == 'schedule' || github.event.inputs.refresh_data == 'true' }} run: sh scripts/deploy.sh "$GITHUB_SHA" diff --git a/.gitea/workflows/validate.yml b/.gitea/workflows/validate.yml index e6f225f..962d585 100644 --- a/.gitea/workflows/validate.yml +++ b/.gitea/workflows/validate.yml @@ -19,9 +19,13 @@ jobs: git checkout -q --detach FETCH_HEAD - name: Install dependencies run: npm ci --no-audit --no-fund + - name: Editor access tests + run: node scripts/test-editor.cjs - name: Type check run: npm run typecheck - name: Build env: NEXT_TELEMETRY_DISABLED: '1' run: npm run build + - name: Access boundary smoke test + run: node scripts/editor-smoke.cjs diff --git a/README.md b/README.md index 8c2afa2..392d624 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,49 @@ npm run data:load ``` `data:build` stages SQLite under `build/` and exports JSONL; `data:load` imports into PostgreSQL and replaces `live`. These commands change data and are not read-only validation. + +## Public journal and editorial access + +The public site now presents only the two initial studies at +`/contents/lean-theorem-proving` and `/contents/tools-of-agents`. `/` retains live +collection counts, and `/contents` lists those studies. Other paper, benchmark, +conference and landscape routes require an editor session. Their database rows +are preserved; this change does not delete or reimport content. + +- `/editor/login`: a six-digit authenticator TOTP code (no password). +- `/editor`: editorial desk and private archive entry. +- `/editor/contents/`: edit text blocks directly (JSON mode for structured content), preview a draft, + then explicitly publish. Preview resolves dynamic blocks without saving. + Publishing replaces the study's blocks immediately; this first editor has no + durable drafts or per-editor accounts. Coordinate edits to avoid overwrites. +- All content and taxonomy APIs, including GET/list endpoints, require the signed + editor cookie. Mutations require the configured Origin. API clients must sign + in through the same authenticator flow; there is no anonymous write fallback. + +Configure these secrets in `/etc/llm-survey/db.env` through your server secret +management process, never in Git or CI logs: + +- `EDITOR_ORIGIN`: the exact browser origin, including port (no trailing slash). + Use HTTPS for internet-facing editorial access; HTTPS enables Secure cookies. +- `EDITOR_TOTP_SECRET`: a random base32 authenticator secret (at least 32 base32 + characters), enrolled privately in the editor's authenticator. TOTP uses SHA-1, + 30-second periods and six digits; server time must be synchronized. +- `EDITOR_SESSION_SECRET`: at least 32 random characters for HMAC-SHA256 sessions. + Rotating this value revokes all sessions. + +Sessions expire after eight hours, are HttpOnly and SameSite=Strict, and can be +ended from the desk. Login attempts are globally limited to ten per five minutes +in persistent `analysis.editor_auth`; accepted TOTP time steps cannot be reused. +Missing configuration leaves editing closed while public studies remain readable. +This is a single shared editorial identity; secret rotation is the recovery +procedure. The existing HTTP public URL can continue serving readers; configure +TLS and the editor secrets before using editorial login over the internet. + +The authenticator QR is provisioned once and delivered privately in chat, never +committed. TOTP-only login is a single possession factor, as requested. + +The deployment job can provision `EDITOR_TOTP_SECRET` and `EDITOR_SESSION_SECRET` +from repository Actions secrets after explicit operator authorization. It writes +them atomically to the existing environment file with mode 0600. Missing secrets +preserve the server configuration. Update `EDITOR_ORIGIN` in the deployment job +when moving editorial access to a TLS domain. diff --git a/components/Layout.tsx b/components/Layout.tsx index 26df5cd..9a200d5 100644 --- a/components/Layout.tsx +++ b/components/Layout.tsx @@ -1,18 +1,9 @@ import Head from 'next/head'; import Link from 'next/link'; -import { useRouter } from 'next/router'; import { ReactNode } from 'react'; -const LINKS = [ - { href: '/', label: 'Home' }, - { href: '/overview', label: 'Overview' }, - { href: '/papers', label: 'Papers' }, - { href: '/landscape', label: 'Landscape' }, - { href: '/contents', label: 'Contents' }, -]; - export default function Layout({ title, children }: { title?: string; children: ReactNode }) { - const { pathname } = useRouter(); + return ( <> @@ -22,11 +13,9 @@ export default function Layout({ title, children }: { title?: string; children:
{children}
diff --git a/lib/api.ts b/lib/api.ts index 6bc1c9f..5ab957d 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -1,4 +1,5 @@ import type { NextApiRequest, NextApiResponse } from 'next'; +import { COOKIE, validSession } from './editor-session'; export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } @@ -10,6 +11,9 @@ type Handler = (req: NextApiRequest) => Promise; /** Dispatch by HTTP method; a handler returns the JSON to send, or throws HttpError. */ export function route(handlers: Partial>) { return async (req: NextApiRequest, res: NextApiResponse) => { + res.setHeader('Cache-Control', 'private, no-store'); + if (!await validSession(req.cookies[COOKIE])) return res.status(401).json({ error: 'Editor authentication required' }); + if (req.method !== 'GET' && (!process.env.EDITOR_ORIGIN || req.headers.origin !== process.env.EDITOR_ORIGIN)) return res.status(403).json({ error: 'Invalid origin' }); const h = handlers[req.method as Method]; if (!h) { res.setHeader('Allow', Object.keys(handlers).join(', ')); diff --git a/lib/editor-session.ts b/lib/editor-session.ts new file mode 100644 index 0000000..6a7477a --- /dev/null +++ b/lib/editor-session.ts @@ -0,0 +1,21 @@ +// Shared with Edge middleware. Only signed, expiring sessions grant editor access. +export const COOKIE = 'atlas_editor'; +const enc = new TextEncoder(); +async function key() { + const secret = process.env.EDITOR_SESSION_SECRET; + if (!secret || secret.length < 32) throw new Error('Editor session secret is not configured'); + return crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']); +} +export async function signSession(value: string) { + return Array.from(new Uint8Array(await crypto.subtle.sign('HMAC', await key(), enc.encode(value)))).map(b => b.toString(16).padStart(2, '0')).join(''); +} +export async function validSession(token?: string) { + if (!token) return false; + const [expires, nonce, signature, extra] = token.split('.'); + if (extra || !/^\d+$/.test(expires) || !/^[a-f0-9]{32}$/.test(nonce) || !/^[a-f0-9]{64}$/.test(signature)) return false; + if (Number(expires) < Date.now() || Number(expires) > Date.now() + 8 * 3600_000) return false; + try { + const bytes = new Uint8Array(signature.match(/../g)!.map(h => parseInt(h, 16))); + return await crypto.subtle.verify('HMAC', await key(), bytes, enc.encode(`${expires}.${nonce}`)); + } catch { return false; } +} diff --git a/lib/totp.ts b/lib/totp.ts new file mode 100644 index 0000000..dd23edc --- /dev/null +++ b/lib/totp.ts @@ -0,0 +1,12 @@ +import { createHmac } from 'crypto'; + +export function totp(secret: string, step: number) { + let bits = ''; for (const c of secret.toUpperCase().replace(/=|\s/g, '')) { + const n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.indexOf(c); if (n < 0) throw new Error('Invalid TOTP secret'); + bits += n.toString(2).padStart(5, '0'); + } + const key = Buffer.from(bits.match(/.{8}/g)!.map(b => parseInt(b, 2))); + const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(step)); + const hash = createHmac('sha1', key).update(counter).digest(); const offset = hash[19] & 15; + return String((hash.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, '0'); +} diff --git a/middleware.ts b/middleware.ts new file mode 100644 index 0000000..dcf3d83 --- /dev/null +++ b/middleware.ts @@ -0,0 +1,23 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { COOKIE, validSession } from './lib/editor-session'; + +export async function middleware(req: NextRequest) { + const path = req.nextUrl.pathname; + if (path === '/editor/login' || path === '/api/editor/login') return NextResponse.next(); + const publicPage = path === '/' || path === '/contents' || /^\/contents\/(lean-theorem-proving|tools-of-agents)$/.test(path); + if (publicPage) return NextResponse.next(); + if (!await validSession(req.cookies.get(COOKIE)?.value)) { + if (path.startsWith('/api/')) return NextResponse.json({ error: 'Editor authentication required' }, { status: 401 }); + if (!path.startsWith('/editor')) return new NextResponse('Not found', { status: 404 }); + const url = req.nextUrl.clone(); url.pathname = '/editor/login'; url.search = ''; + return NextResponse.redirect(url); + } + if (req.method !== 'GET' && req.method !== 'HEAD' && req.headers.get('origin') !== (process.env.EDITOR_ORIGIN || req.nextUrl.origin)) { + return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 }); + } + const response = NextResponse.next(); + response.headers.set('Cache-Control', 'private, no-store'); + response.headers.set('X-Robots-Tag', 'noindex, nofollow'); + return response; +} +export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }; diff --git a/pages/api/editor/login.ts b/pages/api/editor/login.ts new file mode 100644 index 0000000..cfb6b89 --- /dev/null +++ b/pages/api/editor/login.ts @@ -0,0 +1,31 @@ +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.' }); } +} diff --git a/pages/api/editor/logout.ts b/pages/api/editor/logout.ts new file mode 100644 index 0000000..185bbbe --- /dev/null +++ b/pages/api/editor/logout.ts @@ -0,0 +1,7 @@ +import type { NextApiRequest, NextApiResponse } from 'next'; +import { COOKIE } from '../../../lib/editor-session'; +export default function logout(req: NextApiRequest, res: NextApiResponse) { + if (req.method !== 'POST') return res.status(405).end(); + res.setHeader('Set-Cookie', `${COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`); + res.status(200).json({ ok: true }); +} diff --git a/pages/api/editor/preview.ts b/pages/api/editor/preview.ts new file mode 100644 index 0000000..ab46d2c --- /dev/null +++ b/pages/api/editor/preview.ts @@ -0,0 +1,13 @@ +import { route, bodyObject, HttpError } from '../../../lib/api'; +import { validateBlock } from '../../../lib/block-store'; +import { resolveBlocks } from '../../../lib/block-resolve'; +import type { Block, PageBlock } from '../../../lib/blocks'; +export default route({ POST: async req => { + const blocks = bodyObject(req).blocks; + if (!Array.isArray(blocks) || blocks.length > 200) throw new HttpError(400, 'Provide at most 200 blocks'); + const page: PageBlock[] = blocks.map((block: Block, i: number) => { + validateBlock(block?.type, block?.data, `block ${i + 1}`); + return { id: -(i + 1), position: i, revision: 0, updatedAt: 'draft', block }; + }); + return { blocks: await resolveBlocks(page) }; +} }); diff --git a/pages/contents/[node].tsx b/pages/contents/[node].tsx index 76e8698..7cf8e47 100644 --- a/pages/contents/[node].tsx +++ b/pages/contents/[node].tsx @@ -13,6 +13,7 @@ interface Props { node: { id: string; title: string; blurb: string }; blocks: Pa export const getServerSideProps: GetServerSideProps = async ({ params }) => { const node = findNode(String(params?.node)); if (!node || node.id === 'root') return { notFound: true }; + if (!['lean-theorem-proving', 'tools-of-agents'].includes(node.id)) return { notFound: true }; const page = `content/${node.id}`; let blocks = await getBlocks(page); if (!blocks.length) { await seedPage(page, defaultBlocks(node)); blocks = await getBlocks(page); } diff --git a/pages/editor/contents/[node].tsx b/pages/editor/contents/[node].tsx new file mode 100644 index 0000000..537c75c --- /dev/null +++ b/pages/editor/contents/[node].tsx @@ -0,0 +1,132 @@ +import type { GetServerSideProps } from 'next'; +import { useEffect, useRef, useState } from 'react'; +import Link from 'next/link'; +import Layout from '../../../components/Layout'; +import Blocks from '../../../components/Blocks'; +import { findNode } from '../../../lib/content-tree'; +import { getBlocks, seedPage } from '../../../lib/block-store'; +import { defaultBlocks } from '../../../lib/content-defaults'; +import { resolveBlocks } from '../../../lib/block-resolve'; +import type { Block, PageBlock } from '../../../lib/blocks'; + +export const getServerSideProps: GetServerSideProps = async ({ params }) => { + const node = findNode(String(params?.node)); + if (!node || node.id === 'root') return { notFound: true }; + const page = `content/${node.id}`; + let blocks = await getBlocks(page); + if (!blocks.length) { await seedPage(page, defaultBlocks(node)); blocks = await getBlocks(page); } + return { props: { node: node.id, title: node.title, blocks: await resolveBlocks(blocks) } }; +}; + +const serialize = (value: unknown) => JSON.stringify(value, null, 2); +function parseBlock(source: string): Block | null { + try { + const value = JSON.parse(source); + return value && typeof value.type === 'string' && value.data && typeof value.data === 'object' ? value : null; + } catch { return null; } +} + +export default function Workspace({ node, title, blocks }: { node: string; title: string; blocks: PageBlock[] }) { + // Keep each block as source text so incomplete structured edits remain editable. + const [drafts, setDrafts] = useState(() => blocks.map(b => serialize(b.block))); + const [rawSource, setRawSource] = useState(null); + const [preview, setPreview] = useState(blocks); + const [message, setMessage] = useState(''); + const [busy, setBusy] = useState(false); + const published = useRef(false); + const initial = serialize(blocks.map(b => b.block)); + const dirty = rawSource !== null ? rawSource !== initial : serialize(drafts.map(source => { + try { return JSON.parse(source); } catch { return source; } + })) !== initial; + + useEffect(() => { + if (!dirty) return; + const warn = (event: BeforeUnloadEvent) => { if (published.current) return; event.preventDefault(); event.returnValue = ''; }; + window.addEventListener('beforeunload', warn); + // A normal browser navigation receives the same unsaved-draft warning. + return () => window.removeEventListener('beforeunload', warn); + }, [dirty]); + + function draftBlocks(): Block[] { + const value = rawSource !== null ? JSON.parse(rawSource) : drafts.map(source => JSON.parse(source)); + if (!Array.isArray(value) || !value.length) throw new Error('A study needs at least one content block.'); + if (value.some(block => !block || typeof block.type !== 'string' || !block.data || typeof block.data !== 'object')) { + throw new Error('Each block needs a type and a data object.'); + } + return value; + } + function switchMode() { + try { + const value = draftBlocks(); + if (rawSource === null) setRawSource(serialize(value)); + else { setDrafts(value.map(serialize)); setRawSource(null); } + setMessage(''); + } catch (error) { setMessage((error as Error).message); } + } + function update(index: number, value: string) { + setDrafts(current => current.map((source, i) => i === index ? value : source)); + } + function move(index: number, offset: number) { + setDrafts(current => { + const next = [...current]; + [next[index], next[index + offset]] = [next[index + offset], next[index]]; + return next; + }); + } + async function request(previewOnly: boolean) { + setBusy(true); setMessage(''); + try { + const value = draftBlocks(); + const response = await fetch(previewOnly ? '/api/editor/preview' : `/api/blocks?page=${encodeURIComponent(`content/${node}`)}`, { + method: previewOnly ? 'POST' : 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ blocks: value }), + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error); + if (previewOnly) { setPreview(result.blocks); setMessage('Draft preview updated. Nothing has been published.'); } + else { published.current = true; window.location.reload(); } + } catch (error) { setMessage((error as Error).message); } + finally { setBusy(false); } + } + + return + ← Editorial desk +

{title}

+

Write and arrange your research notes, then preview your draft. Unsaved changes are lost when you leave. Publishing updates the public study immediately.

+
+
+
+ + {rawSource === null && } +
+ {rawSource !== null ? <> + +