From 712046e86f4a4e583a697933c297317e5682d3cb Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Fri, 30 Oct 2026 20:02:22 +0800 Subject: [PATCH] Reframe AI-tlas as a public research journal with authenticator-protected editorial workspace --- .gitea/workflows/validate.yml | 4 ++ README.md | 40 ++++++++++++++ components/Layout.tsx | 19 ++----- lib/api.ts | 4 ++ lib/editor-session.ts | 21 ++++++++ middleware.ts | 23 +++++++++ pages/api/editor/login.ts | 40 ++++++++++++++ pages/api/editor/logout.ts | 7 +++ pages/api/editor/preview.ts | 13 +++++ pages/contents/[node].tsx | 1 + pages/editor/contents/[node].tsx | 29 +++++++++++ pages/editor/index.tsx | 6 +++ pages/editor/login.tsx | 15 ++++++ pages/index.tsx | 67 ++++++------------------ scripts/deploy.sh | 2 +- scripts/editor-smoke.cjs | 17 ++++++ scripts/test-editor.cjs | 24 +++++++++ styles/globals.css | 89 ++++++++++++++++++++++++++++++++ 18 files changed, 353 insertions(+), 68 deletions(-) create mode 100644 lib/editor-session.ts create mode 100644 middleware.ts create mode 100644 pages/api/editor/login.ts create mode 100644 pages/api/editor/logout.ts create mode 100644 pages/api/editor/preview.ts create mode 100644 pages/editor/contents/[node].tsx create mode 100644 pages/editor/index.tsx create mode 100644 pages/editor/login.tsx create mode 100644 scripts/editor-smoke.cjs create mode 100644 scripts/test-editor.cjs 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..1f60bee 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,43 @@ 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 ordered JSON content blocks, 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. 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..42d0d0a 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' && 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/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..3fa0cf1 --- /dev/null +++ b/pages/api/editor/login.ts @@ -0,0 +1,40 @@ +import type { NextApiRequest, NextApiResponse } from 'next'; +import { createHmac, randomBytes, timingSafeEqual } from 'crypto'; +import { query } from '../../../lib/db'; +import { COOKIE, signSession } from '../../../lib/editor-session'; + +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'); +} +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..6245edd --- /dev/null +++ b/pages/editor/contents/[node].tsx @@ -0,0 +1,29 @@ +import type { GetServerSideProps } from 'next'; +import { 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 { 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)}}; +}; +export default function Workspace({node,title,blocks}:{node:string;title:string;blocks:PageBlock[]}) { + const [preview,setPreview] = useState(blocks); + const [text,setText] = useState(JSON.stringify(blocks.map(b=>b.block),null,2)); const [message,setMessage] = useState(''); const [busy,setBusy] = useState(false); + async function refreshPreview() { setBusy(true); setMessage(''); try { + const response=await fetch('/api/editor/preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({blocks:JSON.parse(text)})}); + const result=await response.json(); if(!response.ok) throw new Error(result.error); setPreview(result.blocks); + } catch(e) {setMessage((e as Error).message);} finally {setBusy(false);} } + async function publish() { setBusy(true); setMessage(''); try { + const response=await fetch(`/api/blocks?page=${encodeURIComponent(`content/${node}`)}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({blocks:JSON.parse(text)})}); + const result=await response.json(); if(!response.ok) throw new Error(result.error); window.location.reload(); + } catch(e) {setMessage((e as Error).message);} finally {setBusy(false);} } + return ← Editorial desk

{title}

Edit the ordered content blocks, then preview your draft. Unsaved changes are lost when you leave. Publishing updates the public study immediately.