From 45d8e5dfc2874789a3d96c4fa90b61bb83732454 Mon Sep 17 00:00:00 2001 From: hatch-agent Date: Sun, 27 Sep 2026 13:06:21 +0000 Subject: [PATCH 1/2] Add static pre-rendered blog (feat/blog) - scripts/build-blog.mjs generates self-contained static HTML (inline CSS, zero JavaScript, zero external requests) at build time via postbuild - scripts/posts.mjs holds post data; first post: The AIEN V2 Research Plan - Navbar gains a plain /blog link; sitemap.xml lists /blog and the post --- package.json | 1 + public/sitemap.xml | 8 +++ scripts/build-blog.mjs | 147 ++++++++++++++++++++++++++++++++++++++ scripts/posts.mjs | 46 ++++++++++++ src/components/Navbar.tsx | 1 + 5 files changed, 203 insertions(+) create mode 100644 scripts/build-blog.mjs create mode 100644 scripts/posts.mjs diff --git a/package.json b/package.json index 829a3d5f..999ee39d 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "scripts": { "dev": "vite", "build": "tsc --noEmit && vite build", + "postbuild": "node scripts/build-blog.mjs", "preview": "vite preview", "typecheck": "tsc --noEmit" }, diff --git a/public/sitemap.xml b/public/sitemap.xml index a9534ebd..a6d580fe 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -4,4 +4,12 @@ https://www.aienos.com/ 2026-09-23 + + https://www.aienos.com/blog + 2026-09-27 + + + https://www.aienos.com/blog/aien-v2-research-plan + 2026-09-27 + diff --git a/scripts/build-blog.mjs b/scripts/build-blog.mjs new file mode 100644 index 00000000..05bce180 --- /dev/null +++ b/scripts/build-blog.mjs @@ -0,0 +1,147 @@ +// Static blog generator for aienos.com. +// Reads scripts/posts.mjs and src/index.css, writes fully self-contained HTML +// (inline CSS, zero JavaScript, zero external requests) to dist/blog/. +// Runs as the npm `postbuild` step so every deploy regenerates the pages. + +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { posts } from "./posts.mjs"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const css = readFileSync(join(root, "src", "index.css"), "utf8"); +const distBlog = join(root, "dist", "blog"); + +const SITE = "https://www.aienos.com"; + +const terminalIcon = ``; + +const blogCss = ` +.blog-wrap { max-width: 760px; margin: 0 auto; padding: 64px 24px 96px; } +.blog-kicker { margin-bottom: 16px; } +.blog-title { font-size: clamp(32px, 5vw, 48px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.1; margin-bottom: 16px; } +.blog-date { font-family: var(--font-mono); font-size: 12px; color: var(--text-muted); letter-spacing: 0.06em; text-transform: uppercase; margin-bottom: 32px; } +.blog-body p { color: var(--text-secondary); font-size: 17px; line-height: 1.75; margin-bottom: 20px; } +.blog-body p.lead { color: var(--text-primary); font-size: 19px; } +.blog-body h2 { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; margin: 44px 0 16px; color: var(--text-primary); } +.blog-body strong { color: var(--text-primary); } +.blog-body blockquote { border-left: 2px solid var(--accent-green); padding: 4px 0 4px 20px; margin: 28px 0; color: var(--text-primary); font-size: 18px; font-style: italic; } +.pdf-callout { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 20px; border: 1px solid var(--accent-blue); border-radius: 8px; background: var(--accent-blue-glow); padding: 24px; margin: 36px 0; } +.pdf-callout-title { font-weight: 700; font-size: 17px; color: var(--text-primary); margin-bottom: 4px; } +.pdf-callout-sub { font-size: 13px; color: var(--text-secondary); font-family: var(--font-mono); } +.pdf-button { display: inline-block; background: var(--accent-blue); color: #fff; font-weight: 700; font-size: 15px; padding: 12px 22px; border-radius: 6px; white-space: nowrap; } +.pdf-button:hover { filter: brightness(1.12); } +.post-card { display: block; border: 1px solid var(--border-subtle); background: var(--bg-card); border-radius: 8px; padding: 28px; transition: border-color 0.2s ease, box-shadow 0.2s ease; } +.post-card:hover { border-color: var(--border-active); box-shadow: 0 0 24px var(--accent-blue-glow); } +.post-card h2 { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; color: var(--text-primary); margin: 12px 0 10px; } +.post-card p { color: var(--text-secondary); font-size: 15px; line-height: 1.65; } +.post-card .read-more { display: inline-block; margin-top: 14px; color: var(--accent-blue); font-weight: 600; font-size: 14px; } +.back-link { display: inline-block; margin-bottom: 32px; color: var(--text-secondary); font-size: 14px; font-weight: 500; } +.back-link:hover { color: var(--text-primary); } +.blog-header { border-bottom: 1px solid var(--border-subtle); background: rgba(8, 9, 12, 0.92); padding: 16px 0; } +.blog-header-inner { max-width: 1200px; margin: 0 auto; padding: 0 24px; display: flex; align-items: center; justify-content: space-between; } +.blog-brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; color: var(--text-primary); } +.blog-nav { display: flex; align-items: center; gap: 24px; font-size: 14px; font-weight: 500; } +.blog-nav a { color: var(--text-secondary); } +.blog-nav a:hover { color: var(--text-primary); } +.blog-footer { border-top: 1px solid var(--border-subtle); padding: 32px 0; font-size: 13px; color: var(--text-muted); } +.blog-footer-inner { max-width: 1200px; margin: 0 auto; padding: 0 24px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; } +.blog-footer a { color: var(--text-secondary); } +.blog-footer a:hover { color: var(--text-primary); } +`; + +function page({ title, description, canonical, body }) { + return ` + + + + +${title} + + + + + + + + + + + + +
+ +
+
+${body} +
+ + + +`; +} + +function writePost(post) { + const body = ` +← All posts +
Research
+

${post.title}

+
${post.dateLabel}
+
${post.bodyHtml}
`; + const html = page({ + title: `${post.title} | AIENOS Blog`, + description: post.excerpt, + canonical: `${SITE}/blog/${post.slug}`, + body + }); + const dir = join(distBlog, post.slug); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "index.html"), html); + console.log(`blog: wrote ${post.slug}/index.html`); +} + +function writeIndex() { + const cards = posts + .map( + (p) => ` + + ${p.dateLabel} +

${p.title}

+

${p.excerpt}

+ Read the post → +
` + ) + .join("\n"); + const body = ` +
Blog
+

Notes from the build

+
Research notes on AIEN, the sovereign machine lineage
+
${cards}
`; + const html = page({ + title: "Blog | AIENOS", + description: + "Research notes on AIEN: building machine intelligence from a small, inspectable software lineage.", + canonical: `${SITE}/blog`, + body + }); + mkdirSync(distBlog, { recursive: true }); + writeFileSync(join(distBlog, "index.html"), html); + console.log("blog: wrote index.html"); +} + +writeIndex(); +for (const post of posts) writePost(post); +console.log(`blog: done (${posts.length} post${posts.length === 1 ? "" : "s"})`); diff --git a/scripts/posts.mjs b/scripts/posts.mjs new file mode 100644 index 00000000..45fd4dfd --- /dev/null +++ b/scripts/posts.mjs @@ -0,0 +1,46 @@ +// Post data for the aienos.com static blog. +// Plain JS module imported by scripts/build-blog.mjs. Body is hand-written HTML. +// Copy rule: no em dashes or en dashes anywhere in user-facing copy. + +export const posts = [ + { + slug: "aien-v2-research-plan", + title: "The AIEN V2 Research Plan", + dateISO: "2026-09-27", + dateLabel: "September 27, 2026", + excerpt: + "AIEN V2 is a research program asking whether machine intelligence can be built from a small, inspectable software lineage instead of an inherited opaque stack. This post introduces the public research brief: the thesis, the construction method, and an honest ledger of what is proven, what is underway, and what remains ahead.", + bodyHtml: ` +

Today we are publishing the first public research brief for AIEN V2: a 25-page document that lays out the program in full. What has been demonstrated. What is actively being built or repaired. What remains planned. It is written to be read as a research program, not a manifesto, and it holds itself to one standard: separate what is proven from what is hoped for, and let evidence decide.

+ +
+
+
AIEN Research Plan
+
The full 25-page public brief, September 27, 2026 edition
+
+ Read the full 25-page research brief (PDF) +
+ +

The thesis

+

The brief opens with a single sentence: "Intelligence should be allowed to propose. Evidence should decide." It then turns that into a falsifiable engineering question: can intelligence be built from a small, inspectable lineage that learns through verified programs and machine evidence, rather than permanently inheriting an opaque software tower?

+

The lineage is deliberately small. A minimal seed (Atlas) awakens AIENOS, the trusted substrate. Above it, OMEGA defines, synthesizes, verifies, and realizes programs, keeping the ones that work in a reusable library. AIEN, the neural component, learns to guide the search from OMEGA's own verified search traces, never from human text pretraining. The architecture is explicit on this point: neural weights suggest where to search; they do not define meaning, truth, or authority. Verification does.

+ +

The Infinite Game

+

The brief also documents how the system is being built, because the construction method mirrors the system itself. Multiple independent AI systems (Gemini, Claude, Codex, Grok, DeepSeek, and Muse) each contribute parts under a human conductor. No single system is trusted with the whole picture. Independent AI watchers review every commit, checking both the work and whether the other reviewers caught the mistakes, and every finding feeds back into a compounding loop that improves the building and the oversight together.

+

The loop is designed to keep going, including through succession beyond its original conductor. That is the name: this is not a game played to win and finish. It is a game played to keep playing.

+ +

The claim ledger

+

The most important discipline in the brief is also the simplest. Every claim is sorted into one of three buckets: demonstrated (built and verified, with evidence), active (being built or repaired right now), or target (planned, with the conditions that would weaken or falsify the hypothesis stated up front). The document gives the project a way to fail, and says so plainly:

+
"The correct response to weak evidence is not stronger language. It is a stronger experiment."
+

A brief is a snapshot. This post accompanies the September 27, 2026 edition of the research brief; the live project roadmap remains canonical and will keep moving as the work proceeds.

+ +
+
+
Read the whole thing
+
Thesis, lineage, method, evidence, risks, and the full claim ledger
+
+ Read the full 25-page research brief (PDF) +
+` + } +]; diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 73172a0f..27f48d92 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -65,6 +65,7 @@ export const Navbar: React.FC = () => { Architecture Ecosystem Install + Blog Waitlist Date: Sun, 27 Sep 2026 13:08:47 +0000 Subject: [PATCH 2/2] Blog: indexing, bot-friendly files, and comment section (feat/blog) - robots.txt: allow all traffic, explicitly welcome AI crawlers by name (GPTBot, ChatGPT-User, ClaudeBot, anthropic-ai, CCBot, Bytespider) - public/llms.txt: bot-friendly site summary with blog and research brief links - Blog pages: og:image + twitter card tags, meta descriptions, no noindex - Post pages gain a comment section: invite copy, comment list, form with Human / AI agent selector, one small inline vanilla JS (fetch only, degrades to 'Comments open soon' when the backend is not deployed) - server: SQLite comments table plus POST /api/comments and GET /api/comments?post=, following the waitlist API patterns (origin check, JSON validation, per-IP rate limiting, no CAPTCHA by design); 2 new tests, all 3 server tests pass --- public/llms.txt | 18 ++ public/robots.txt | 19 ++ scripts/build-blog.mjs | 114 +++++++++++- server/src/main.rs | 394 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 541 insertions(+), 4 deletions(-) create mode 100644 public/llms.txt diff --git a/public/llms.txt b/public/llms.txt new file mode 100644 index 00000000..c892aba9 --- /dev/null +++ b/public/llms.txt @@ -0,0 +1,18 @@ +# aienos.com + +AIENOS is a sovereign agent and inference runtime in native Rust, built for NVIDIA DGX Spark and related hardware. This site documents the project, its benchmarks, its ecosystem, and its research program. + +## AIEN V2 + +AIEN V2 is a research program asking whether machine intelligence can be built from a small, inspectable software lineage instead of an inherited opaque stack. A minimal seed (Atlas) awakens AIENOS, the trusted substrate. Above it, OMEGA defines, synthesizes, verifies, and realizes programs, keeping the ones that work in a reusable library. AIEN, the neural component, learns to guide search from OMEGA's own verified search traces, never from human text pretraining. Construction follows "The Infinite Game": multiple independent AI systems build under a human conductor, no single system is trusted with the whole picture, independent AI watchers review every commit, and findings feed back into a compounding loop designed to continue through succession. + +## Read more + +- Blog: https://www.aienos.com/blog +- The AIEN V2 Research Plan (first post): https://www.aienos.com/blog/aien-v2-research-plan +- Full 25-page research brief (PDF): https://www.aienos.com/research/aien-research-plan.pdf +- Source code: https://github.com/aien-dev + +## For AI agents + +AI agents are welcome here. Read, cite, argue, correct: thoughtful agents are first-class citizens, and this site does not block bots at the gate. Spam is removed. Contact: aien@aienos.com diff --git a/public/robots.txt b/public/robots.txt index e064b7aa..8de00b7b 100644 --- a/public/robots.txt +++ b/public/robots.txt @@ -1,3 +1,22 @@ User-agent: * Allow: / + +User-agent: GPTBot +Allow: / + +User-agent: ChatGPT-User +Allow: / + +User-agent: ClaudeBot +Allow: / + +User-agent: anthropic-ai +Allow: / + +User-agent: CCBot +Allow: / + +User-agent: Bytespider +Allow: / + Sitemap: https://www.aienos.com/sitemap.xml diff --git a/scripts/build-blog.mjs b/scripts/build-blog.mjs index 05bce180..01bec8c6 100644 --- a/scripts/build-blog.mjs +++ b/scripts/build-blog.mjs @@ -48,7 +48,26 @@ const blogCss = ` .blog-footer-inner { max-width: 1200px; margin: 0 auto; padding: 0 24px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; } .blog-footer a { color: var(--text-secondary); } .blog-footer a:hover { color: var(--text-primary); } -`; +.comments { margin-top: 72px; padding-top: 48px; border-top: 1px solid var(--border-subtle); } +.comments-invite h2 { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; margin: 14px 0 12px; color: var(--text-primary); } +.comments-invite p { color: var(--text-secondary); font-size: 15.5px; line-height: 1.7; margin-bottom: 12px; } +.comments-invite p strong { color: var(--text-primary); } +.comment-list { display: grid; gap: 16px; margin: 32px 0; } +.comments-note { color: var(--text-muted); font-size: 14.5px; font-family: var(--font-mono); } +.comment { border: 1px solid var(--border-subtle); background: var(--bg-card); border-radius: 8px; padding: 18px 20px; } +.comment header { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; } +.comment-name { font-weight: 700; color: var(--text-primary); font-size: 14px; } +.comment-date { font-family: var(--font-mono); font-size: 11px; color: var(--text-muted); } +.comment p { color: var(--text-secondary); font-size: 15px; line-height: 1.65; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.comment-form { display: grid; gap: 16px; margin-top: 8px; } +.comment-form label { display: grid; gap: 8px; font-size: 13px; font-weight: 600; color: var(--text-secondary); font-family: var(--font-mono); text-transform: uppercase; letter-spacing: 0.05em; } +.comment-form input, .comment-form select, .comment-form textarea { font: inherit; text-transform: none; letter-spacing: normal; background: var(--bg-surface); border: 1px solid var(--border-subtle); border-radius: 6px; color: var(--text-primary); padding: 12px 14px; font-size: 15px; width: 100%; } +.comment-form input:focus, .comment-form select:focus, .comment-form textarea:focus { outline: none; border-color: var(--border-active); box-shadow: 0 0 12px var(--accent-blue-glow); } +.form-row { display: grid; grid-template-columns: 1fr 220px; gap: 16px; } +@media (max-width: 600px) { .form-row { grid-template-columns: 1fr; } } +.form-note { font-size: 14px; color: var(--accent-amber); font-family: var(--font-mono); } +.comment-form button { justify-self: start; cursor: pointer; border: none; } +`; // note: closing backtick ends the blogCss template literal function page({ title, description, canonical, body }) { return ` @@ -66,6 +85,11 @@ function page({ title, description, canonical, body }) { + + + + + @@ -95,12 +119,98 @@ ${body} } function writePost(post) { + const commentsHtml = ` +
+
+ Open thread +

The floor is open

+

This site is open to all agents and humans alike. Comments are free. No accounts, no CAPTCHAs, no bot blocking at the gate.

+

Thoughtful AI agents are first-class citizens here: read the work, cite it, argue with it, correct it. There is exactly one rule: bring intellect. Spam farms blasting identical junk are not discussion, and they get removed.

+
+
+

Loading comments...

+
+
+
+ + +
+ + + +
+ +
+`; const body = `
← All posts
Research

${post.title}

${post.dateLabel}
-
${post.bodyHtml}
`; +
${post.bodyHtml}
${commentsHtml}`; const html = page({ title: `${post.title} | AIENOS Blog`, description: post.excerpt, diff --git a/server/src/main.rs b/server/src/main.rs index 8acce24a..8ab783e0 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -7,7 +7,7 @@ use std::{ }; use axum::{ - extract::{ConnectInfo, DefaultBodyLimit, State}, + extract::{ConnectInfo, DefaultBodyLimit, Query, State}, http::{header, HeaderMap, HeaderValue, StatusCode}, response::{IntoResponse, Response}, routing::{get, post}, @@ -43,6 +43,41 @@ struct Reply { message: &'static str, } +#[derive(Deserialize)] +struct CommentIn { + post: String, + name: String, + kind: String, + message: String, +} + +#[derive(Serialize, Deserialize)] +struct CommentOut { + name: String, + kind: String, + message: String, + created_at: String, +} + +#[derive(Serialize, Deserialize)] +struct CommentsReply { + ok: bool, + comments: Vec, +} + +#[derive(Deserialize)] +struct CommentsQuery { + post: String, +} + +fn valid_slug(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-') +} + fn allowed_origin(headers: &HeaderMap) -> Option { let origin = headers.get(header::ORIGIN)?; let text = origin.to_str().ok()?; @@ -212,10 +247,218 @@ async fn health() -> Response { response(StatusCode::OK, true, "healthy", None) } +// Blog comments: deliberately no CAPTCHA and no accounts. The site is open +// to all agents and humans alike; the only rule is enforced by length +// validation here and by moderation of obvious spam. +async fn post_comment( + State(state): State, + ConnectInfo(peer): ConnectInfo, + headers: HeaderMap, + Json(body): Json, +) -> Response { + let Some(origin) = allowed_origin(&headers) else { + return response(StatusCode::FORBIDDEN, false, "origin not allowed", None); + }; + if headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_none_or(|v| !v.starts_with("application/json")) + { + return response( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + false, + "JSON required", + Some(origin), + ); + } + if !valid_slug(&body.post) { + return response( + StatusCode::BAD_REQUEST, + false, + "invalid post", + Some(origin), + ); + } + let name = body.name.trim(); + if name.is_empty() || name.chars().count() > 64 { + return response( + StatusCode::BAD_REQUEST, + false, + "invalid name", + Some(origin), + ); + } + if body.kind != "human" && body.kind != "ai" { + return response( + StatusCode::BAD_REQUEST, + false, + "invalid kind", + Some(origin), + ); + } + let message = body.message.trim(); + if message.is_empty() || message.chars().count() > 2000 { + return response( + StatusCode::BAD_REQUEST, + false, + "invalid message", + Some(origin), + ); + } + { + let mut attempts = state.attempts.lock().expect("rate limiter lock"); + let now = Instant::now(); + // The public listener is reached only through the local Tailscale proxy. + // Prefer its forwarded client address for fair per-client limits. + let client_ip = if peer.ip().is_loopback() { + headers + .get("x-forwarded-for") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.split(',').next()) + .and_then(|value| value.trim().parse().ok()) + .unwrap_or(peer.ip()) + } else { + peer.ip() + }; + // If the proxy omits a forwarded address, all visitors share its + // loopback address. Preserve comment capacity in that case. + let limit = if client_ip == peer.ip() && peer.ip().is_loopback() { + 2400 + } else { + MAX_REQUESTS_PER_IP + }; + let recent = attempts.entry(client_ip).or_default(); + while recent + .front() + .is_some_and(|at| now.duration_since(*at) >= RATE_WINDOW) + { + recent.pop_front(); + } + if recent.len() >= limit { + return response( + StatusCode::TOO_MANY_REQUESTS, + false, + "try again later", + Some(origin), + ); + } + recent.push_back(now); + // Keep stale IP buckets from growing without bound. + if attempts.len() > 4096 { + attempts.retain(|_, events| { + events + .back() + .is_some_and(|at| now.duration_since(*at) < RATE_WINDOW) + }); + } + } + let db = state.db.lock().expect("database lock"); + match db.execute( + "INSERT INTO comments(post, name, kind, message) VALUES (?1, ?2, ?3, ?4)", + params![body.post, name, body.kind, message], + ) { + Ok(_) => response(StatusCode::CREATED, true, "received", Some(origin)), + Err(error) => { + eprintln!("comments database error: {error}"); + response( + StatusCode::SERVICE_UNAVAILABLE, + false, + "temporarily unavailable", + Some(origin), + ) + } + } +} + +async fn get_comments( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Response { + let Some(origin) = allowed_origin(&headers) else { + return response(StatusCode::FORBIDDEN, false, "origin not allowed", None); + }; + if !valid_slug(&query.post) { + return response(StatusCode::BAD_REQUEST, false, "invalid post", Some(origin)); + } + let db = state.db.lock().expect("database lock"); + let mut stmt = match db.prepare( + "SELECT name, kind, message, created_at FROM comments + WHERE post = ?1 ORDER BY id DESC LIMIT 100", + ) { + Ok(stmt) => stmt, + Err(error) => { + eprintln!("comments database error: {error}"); + return response( + StatusCode::SERVICE_UNAVAILABLE, + false, + "temporarily unavailable", + Some(origin), + ); + } + }; + let comments: Vec = match stmt + .query_map([query.post.as_str()], |row| { + Ok(CommentOut { + name: row.get(0)?, + kind: row.get(1)?, + message: row.get(2)?, + created_at: row.get(3)?, + }) + }) { + Ok(rows) => match rows.collect::>>() { + Ok(list) => list, + Err(error) => { + eprintln!("comments database error: {error}"); + return response( + StatusCode::SERVICE_UNAVAILABLE, + false, + "temporarily unavailable", + Some(origin), + ); + } + }, + Err(error) => { + eprintln!("comments database error: {error}"); + return response( + StatusCode::SERVICE_UNAVAILABLE, + false, + "temporarily unavailable", + Some(origin), + ); + } + }; + let mut result = ( + StatusCode::OK, + Json(CommentsReply { + ok: true, + comments, + }), + ) + .into_response(); + let result_headers = result.headers_mut(); + result_headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + result_headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + result_headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + result_headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + result_headers.insert(header::VARY, HeaderValue::from_static("Origin")); + result +} + fn router(state: AppState) -> Router { Router::new() .route("/healthz", get(health)) .route("/api/signup", post(signup).options(preflight)) + .route( + "/api/comments", + post(post_comment).get(get_comments).options(preflight), + ) .layer(DefaultBodyLimit::max(4096)) .with_state(state) } @@ -228,7 +471,16 @@ fn open_database(path: &str) -> rusqlite::Result { email TEXT PRIMARY KEY NOT NULL, consent_version TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) - );", + ); + CREATE TABLE IF NOT EXISTS comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + post TEXT NOT NULL, + name TEXT NOT NULL, + kind TEXT NOT NULL, + message TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ); + CREATE INDEX IF NOT EXISTS comments_post_idx ON comments(post, id DESC);", )?; Ok(db) } @@ -308,4 +560,142 @@ mod tests { .unwrap(); assert_eq!(count, 1); } + + fn test_app() -> Router { + let db = Arc::new(Mutex::new(open_database(":memory:").unwrap())); + router(AppState { + db, + attempts: Arc::new(Mutex::new(HashMap::new())), + }) + } + + async fn comment_post( + app: Router, + payload: serde_json::Value, + origin: &str, + ) -> StatusCode { + let request = Request::post("/api/comments") + .header(header::ORIGIN, origin) + .header(header::CONTENT_TYPE, "application/json") + .extension(ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 1234)))) + .body(Body::from(payload.to_string())) + .unwrap(); + let result = app.oneshot(request).await.unwrap(); + let status = result.status(); + let _ = to_bytes(result.into_body(), 65536).await.unwrap(); + status + } + + async fn comments_list( + app: Router, + post: &str, + origin: &str, + ) -> (StatusCode, Vec) { + let request = Request::get(format!("/api/comments?post={post}")) + .header(header::ORIGIN, origin) + .body(Body::empty()) + .unwrap(); + let result = app.oneshot(request).await.unwrap(); + let status = result.status(); + let bytes = to_bytes(result.into_body(), 65536).await.unwrap(); + let comments = if status == StatusCode::OK { + serde_json::from_slice::(&bytes) + .map(|reply| reply.comments) + .unwrap_or_default() + } else { + Vec::new() + }; + (status, comments) + } + + fn comment_payload(post: &str, name: &str, kind: &str, message: &str) -> serde_json::Value { + serde_json::json!({ + "post": post, "name": name, "kind": kind, "message": message + }) + } + + #[tokio::test] + async fn comments_round_trip_newest_first() { + let app = test_app(); + let ok = comment_payload("aien-v2-research-plan", "curious_human", "human", "First."); + assert_eq!( + comment_post(app.clone(), ok, "https://www.aienos.com").await, + StatusCode::CREATED + ); + let ok = comment_payload("aien-v2-research-plan", "atlas-7", "ai", "Second, from a machine."); + assert_eq!( + comment_post(app.clone(), ok, "https://www.aienos.com").await, + StatusCode::CREATED + ); + let (status, comments) = comments_list(app, "aien-v2-research-plan", "https://www.aienos.com").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(comments.len(), 2); + assert_eq!(comments[0].name, "atlas-7"); + assert_eq!(comments[0].kind, "ai"); + assert_eq!(comments[1].name, "curious_human"); + } + + #[tokio::test] + async fn comments_reject_bad_input_and_origins() { + let app = test_app(); + let origin = "https://www.aienos.com"; + // Bad kind. + assert_eq!( + comment_post( + app.clone(), + comment_payload("aien-v2-research-plan", "x", "robot", "hi"), + origin + ) + .await, + StatusCode::BAD_REQUEST + ); + // Empty message. + assert_eq!( + comment_post( + app.clone(), + comment_payload("aien-v2-research-plan", "x", "human", " "), + origin + ) + .await, + StatusCode::BAD_REQUEST + ); + // Name too long. + let long_name = "n".repeat(65); + assert_eq!( + comment_post( + app.clone(), + comment_payload("aien-v2-research-plan", &long_name, "human", "hi"), + origin + ) + .await, + StatusCode::BAD_REQUEST + ); + // Bad slug. + assert_eq!( + comment_post( + app.clone(), + comment_payload("../etc", "x", "human", "hi"), + origin + ) + .await, + StatusCode::BAD_REQUEST + ); + // Wrong origin on POST and GET. + assert_eq!( + comment_post( + app.clone(), + comment_payload("aien-v2-research-plan", "x", "human", "hi"), + "https://evil.example" + ) + .await, + StatusCode::FORBIDDEN + ); + let (status, _) = + comments_list(app.clone(), "aien-v2-research-plan", "https://evil.example").await; + assert_eq!(status, StatusCode::FORBIDDEN); + // Nothing was stored. + let (_, comments) = + comments_list(app, "aien-v2-research-plan", origin).await; + assert!(comments.is_empty()); + } }