Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.
TypeScript agent-memoryai-agentsanthropicclaude-codecursorgitknowledge-baseknowledge-graphllmmarkdownmcpmcp-servermodel-context-protocolnote-takingobsidianpkmragsecond-brainself-hostedzettelkasten
P5: auth (Google + allowlist) + vault boot-clone + deploy docs
Ronalds Palacis3d8ed1cb312e
diff --git a/.env.example b/.env.exampleindex ea5f6cc..43c91e1 100644--- a/.env.example+++ b/.env.example@@ -19,9 +19,10 @@ GIT_AUTHOR_EMAIL="[email protected]"# ── Auth ────────────────────────────────────────────────────────────────────# Dashboard: Google sign-in restricted to an email allowlist.-ALLOWED_EMAILS=""-BETTER_AUTH_SECRET="" # openssl rand -base64 32-BETTER_AUTH_URL="http://localhost:3000"+# Leave AUTH_SECRET empty (or AUTH_DISABLED=true) to keep the dashboard OPEN (local dev).+ALLOWED_EMAILS="" # comma-separated emails allowed to sign in+AUTH_SECRET="" # openssl rand -base64 32 (empty => auth off)+APP_URL="http://localhost:3000" # public base URL (Google OAuth redirect_uri = APP_URL/api/auth/callback)GOOGLE_CLIENT_ID=""GOOGLE_CLIENT_SECRET=""@@ -30,3 +31,8 @@ MCP_TOKEN=""# Local/OSS single-user mode: no Google auth, MCP open. NEVER true in production.AUTH_DISABLED="false"++# ── Harness (brain_capture) ──────────────────────────────────────────────────+# Anthropic key for auto-filing rough dumps. Optional (capture disabled if unset).+ANTHROPIC_API_KEY=""+CAPTURE_MODEL="claude-haiku-4-5-20251001"diff --git a/DEPLOY.md b/DEPLOY.mdnew file mode 100644index 0000000..9e2c7f1--- /dev/null+++ b/DEPLOY.md@@ -0,0 +1,58 @@+# Deploying Cortex++Cortex deploys as one container. The **app** repo is this repo; the **vault** is a separate+remote repo the app clones + git-syncs into a volume. No machine keeps a local vault copy.++## 1. Push this repo to GitHub+Already a git repo. Create a remote (private is fine) and push `main`.++## 2. Create the vault repo (if you don't have one)+A separate repo of markdown (e.g. `youruser/second-brain`). Cortex clones it into its volume.+Give it the folders in `SCHEMA.md` (`clients/`, `decisions/`, …).++## 3. Google OAuth (dashboard login)+1. Google Cloud Console → **APIs & Services → Credentials → Create OAuth client ID** → **Web application**.+2. **Authorized redirect URI:** `https://<your-app>.up.railway.app/api/auth/callback`+3. Copy the **Client ID** and **Client secret**.++## 4. Railway+1. **New Project → Deploy from GitHub repo** → this repo. It builds via the root `Dockerfile`.+2. **Add a Volume**, mount path `/data`.+3. **Variables:**++| Variable | Value |+|---|---|+| `NEXT_PUBLIC_APP_NAME` | e.g. `Klyiro Brain` |+| `VAULT_DIR` | `/data` |+| `GIT_REMOTE` | the vault repo URL (`https://github.com/youruser/second-brain.git`) |+| `GIT_TOKEN` | GitHub token with **push** access to the vault repo |+| `GIT_SYNC_ENABLED` | `true` |+| `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | commit identity |+| `AUTH_SECRET` | `openssl rand -base64 32` |+| `APP_URL` | `https://<your-app>.up.railway.app` |+| `ALLOWED_EMAILS` | comma-separated team emails |+| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | from step 3 |+| `MCP_TOKEN` | a long random string (agents send this) |+| `ANTHROPIC_API_KEY` | for `brain_capture` (optional) |++4. Deploy. On first boot the app clones `GIT_REMOTE` into `/data`. The dashboard is gated by+ Google login (allowlist); the MCP is gated by `MCP_TOKEN`.++## 5. Connect agents to the MCP+**Claude Code:**+```bash+claude mcp add --transport http cortex https://<your-app>.up.railway.app/api/mcp \+ --header "Authorization: Bearer $MCP_TOKEN"+```+**Hermes** (`~/.hermes/config.yaml`):+```yaml+mcp_servers:+ cortex:+ url: https://<your-app>.up.railway.app/api/mcp+ headers:+ Authorization: "Bearer <MCP_TOKEN>"+```++## Notes+- **No auth locally:** leave `AUTH_SECRET` empty (or `AUTH_DISABLED=true`) and the dashboard is open.+- **Security:** never expose the MCP without `MCP_TOKEN`. Rotate `GIT_TOKEN` if leaked.diff --git a/app/api/auth/callback/route.ts b/app/api/auth/callback/route.tsnew file mode 100644index 0000000..6e4301a--- /dev/null+++ b/app/api/auth/callback/route.ts@@ -0,0 +1,38 @@+import { createSessionToken, exchangeCodeForUser, isAllowed } from "@/lib/auth";+import { APP_URL, SESSION_COOKIE } from "@/lib/config";++export const dynamic = "force-dynamic";++function parseCookies(header: string): Record<string, string> {+ const out: Record<string, string> = {};+ for (const part of header.split(";")) {+ const i = part.indexOf("=");+ if (i > -1) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());+ }+ return out;+}++function redirect(path: string, setCookie?: string) {+ const headers: Record<string, string> = { location: path };+ if (setCookie) headers["set-cookie"] = setCookie;+ return new Response(null, { status: 302, headers });+}++export async function GET(req: Request) {+ const url = new URL(req.url);+ const code = url.searchParams.get("code");+ const state = url.searchParams.get("state");+ const cookies = parseCookies(req.headers.get("cookie") || "");+ if (!code || !state || cookies.oauth_state !== state) return redirect("/login?error=state");++ const user = await exchangeCodeForUser(code);+ if (!user) return redirect("/login?error=google");+ if (!isAllowed(user.email)) return redirect("/login?error=not-allowed");++ const token = await createSessionToken(user);+ const secure = APP_URL.startsWith("https");+ return redirect(+ "/",+ `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${60 * 60 * 24 * 30}${secure ? "; Secure" : ""}`,+ );+}diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.tsnew file mode 100644index 0000000..c8fe218--- /dev/null+++ b/app/api/auth/login/route.ts@@ -0,0 +1,17 @@+import { googleAuthUrl } from "@/lib/auth";+import { APP_URL, GOOGLE_CLIENT_ID } from "@/lib/config";++export const dynamic = "force-dynamic";++export function GET() {+ if (!GOOGLE_CLIENT_ID) return Response.json({ error: "Google auth not configured" }, { status: 500 });+ const state = crypto.randomUUID();+ const secure = APP_URL.startsWith("https");+ return new Response(null, {+ status: 302,+ headers: {+ location: googleAuthUrl(state),+ "set-cookie": `oauth_state=${state}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${secure ? "; Secure" : ""}`,+ },+ });+}diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.tsnew file mode 100644index 0000000..83667dc--- /dev/null+++ b/app/api/auth/logout/route.ts@@ -0,0 +1,10 @@+import { SESSION_COOKIE } from "@/lib/config";++export const dynamic = "force-dynamic";++export function GET() {+ return new Response(null, {+ status: 302,+ headers: { location: "/login", "set-cookie": `${SESSION_COOKIE}=; Path=/; HttpOnly; Max-Age=0` },+ });+}diff --git a/app/login/page.tsx b/app/login/page.tsxnew file mode 100644index 0000000..9200d29--- /dev/null+++ b/app/login/page.tsx@@ -0,0 +1,31 @@+const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME || "Cortex";++export default async function LoginPage({+ searchParams,+}: {+ searchParams: Promise<{ error?: string }>;+}) {+ const { error } = await searchParams;+ const msg =+ error === "not-allowed"+ ? "That account isn't on the allowlist."+ : error+ ? "Sign-in failed. Please try again."+ : null;++ return (+ <div className="flex min-h-dvh flex-col items-center justify-center gap-6 px-6">+ <div className="flex items-center gap-2">+ <div className="size-2 rounded-full bg-primary" />+ <span className="text-lg font-medium tracking-tight">{APP_NAME}</span>+ </div>+ <a+ href="/api/auth/login"+ className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-opacity hover:opacity-90"+ >+ Sign in with Google+ </a>+ {msg && <p className="text-sm text-destructive">{msg}</p>}+ </div>+ );+}diff --git a/bun.lock b/bun.lockindex 77709da..dd947d9 100644--- a/bun.lock+++ b/bun.lock@@ -14,6 +14,7 @@"d3-force": "^3.0.0","date-fns": "^4.4.0","gray-matter": "^4.0.3",+ "jose": "^6.2.3","lucide-react": "^1.17.0","minisearch": "^7.1.2","next": "16.2.7",diff --git a/instrumentation.ts b/instrumentation.tsnew file mode 100644index 0000000..9d3c26b--- /dev/null+++ b/instrumentation.ts@@ -0,0 +1,7 @@+// Runs once when the server starts. Used to clone the remote vault into VAULT_DIR+// on first boot (production). No-op unless GIT_SYNC_ENABLED + GIT_REMOTE are set.+export async function register() {+ if (process.env.NEXT_RUNTIME !== "nodejs") return;+ const { ensureVaultRepo } = await import("@/lib/git");+ await ensureVaultRepo();+}diff --git a/lib/auth.ts b/lib/auth.tsnew file mode 100644index 0000000..1c52a9b--- /dev/null+++ b/lib/auth.ts@@ -0,0 +1,75 @@+import { SignJWT, jwtVerify } from "jose";+import {+ ALLOWED_EMAILS,+ APP_URL,+ AUTH_SECRET,+ GOOGLE_CLIENT_ID,+ GOOGLE_CLIENT_SECRET,+} from "@/lib/config";++const key = () => new TextEncoder().encode(AUTH_SECRET);++export interface Session {+ email: string;+ name?: string;+}++export async function createSessionToken(session: Session): Promise<string> {+ return new SignJWT({ email: session.email, name: session.name })+ .setProtectedHeader({ alg: "HS256" })+ .setIssuedAt()+ .setExpirationTime("30d")+ .sign(key());+}++export async function verifySessionToken(token: string): Promise<Session | null> {+ try {+ const { payload } = await jwtVerify(token, key());+ return { email: payload.email as string, name: payload.name as string | undefined };+ } catch {+ return null;+ }+}++/** An email is allowed only if it's on the allowlist. Empty allowlist => nobody. */+export function isAllowed(email: string): boolean {+ return ALLOWED_EMAILS.length > 0 && ALLOWED_EMAILS.includes(email.toLowerCase());+}++const REDIRECT_URI = () => `${APP_URL}/api/auth/callback`;++export function googleAuthUrl(state: string): string {+ const p = new URLSearchParams({+ client_id: GOOGLE_CLIENT_ID,+ redirect_uri: REDIRECT_URI(),+ response_type: "code",+ scope: "openid email profile",+ state,+ access_type: "online",+ prompt: "select_account",+ });+ return `https://accounts.google.com/o/oauth2/v2/auth?${p.toString()}`;+}++export async function exchangeCodeForUser(code: string): Promise<Session | null> {+ const tokenRes = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ code,+ client_id: GOOGLE_CLIENT_ID,+ client_secret: GOOGLE_CLIENT_SECRET,+ redirect_uri: REDIRECT_URI(),+ grant_type: "authorization_code",+ }),+ });+ if (!tokenRes.ok) return null;+ const { access_token } = await tokenRes.json();+ const uiRes = await fetch("https://openidconnect.googleapis.com/v1/userinfo", {+ headers: { authorization: `Bearer ${access_token}` },+ });+ if (!uiRes.ok) return null;+ const ui = await uiRes.json();+ if (!ui.email) return null;+ return { email: ui.email as string, name: ui.name as string | undefined };+}diff --git a/lib/config.ts b/lib/config.tsindex 3054335..6ba4d39 100644--- a/lib/config.ts+++ b/lib/config.ts@@ -33,6 +33,15 @@ export const ALLOWED_EMAILS = (process.env.ALLOWED_EMAILS ?? "")/** Single-user / local mode: no Google auth, MCP open. For OSS local dev only. */export const AUTH_DISABLED = process.env.AUTH_DISABLED === "true";+/** Session-cookie signing secret. When empty, dashboard auth is OFF (local dev). */+export const AUTH_SECRET = process.env.AUTH_SECRET ?? "";+/** Public base URL (for the Google OAuth redirect_uri). */+export const APP_URL = process.env.APP_URL ?? "http://localhost:3000";+export const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID ?? "";+export const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET ?? "";++export const SESSION_COOKIE = "cortex_session";+/** When true, the git-sync loop commits + pushes vault changes to the remote. */export const GIT_SYNC_ENABLED = process.env.GIT_SYNC_ENABLED === "true";diff --git a/lib/git.ts b/lib/git.tsindex e46bfd0..1fa02eb 100644--- a/lib/git.ts+++ b/lib/git.ts@@ -1,6 +1,31 @@+import fs from "node:fs";+import path from "node:path";import { simpleGit, type SimpleGit } from "simple-git";import { VAULT_DIR, GIT_SYNC_ENABLED } from "@/lib/config";+/**+ * On boot: if GIT_SYNC is on and VAULT_DIR isn't yet a git repo, clone GIT_REMOTE+ * into it. This is how the deployed app populates its volume from the remote vault+ * repo — so no machine keeps a local copy, the server just checks one out.+ */+export async function ensureVaultRepo(): Promise<void> {+ if (!GIT_SYNC_ENABLED) return;+ const remote = process.env.GIT_REMOTE;+ if (!remote) return;+ if (fs.existsSync(path.join(VAULT_DIR, ".git"))) return;+ const token = process.env.GIT_TOKEN;+ const url = token && remote.startsWith("https://")+ ? remote.replace("https://", `https://x-access-token:${token}@`)+ : remote;+ try {+ fs.mkdirSync(VAULT_DIR, { recursive: true });+ await simpleGit().clone(url, VAULT_DIR);+ console.log(`[git] cloned vault repo into ${VAULT_DIR}`);+ } catch (e) {+ console.error("[git] vault clone failed", e);+ }+}+let git: SimpleGit | null = null;function getGit(): SimpleGit {if (!git) git = simpleGit(VAULT_DIR);diff --git a/middleware.ts b/middleware.tsnew file mode 100644index 0000000..ad871ef--- /dev/null+++ b/middleware.ts@@ -0,0 +1,35 @@+import { NextResponse, type NextRequest } from "next/server";+import { jwtVerify } from "jose";++const SESSION_COOKIE = "cortex_session";++export async function middleware(req: NextRequest) {+ const secret = process.env.AUTH_SECRET || "";+ // Auth is OFF unless explicitly configured (secret present and not disabled).+ // This keeps local dev open out of the box and only gates once secrets are set.+ if (process.env.AUTH_DISABLED === "true" || !secret) return NextResponse.next();++ const token = req.cookies.get(SESSION_COOKIE)?.value;+ let ok = false;+ if (token) {+ try {+ await jwtVerify(token, new TextEncoder().encode(secret));+ ok = true;+ } catch {+ ok = false;+ }+ }+ if (!ok) {+ const url = req.nextUrl.clone();+ url.pathname = "/login";+ url.search = "";+ return NextResponse.redirect(url);+ }+ return NextResponse.next();+}++export const config = {+ // Protect everything except the MCP endpoint (bearer-token), health, the auth+ // routes, the login page, and static assets.+ matcher: ["/((?!api/mcp|api/health|api/auth|login|_next/static|_next/image|favicon.ico).*)"],+};diff --git a/package.json b/package.jsonindex 4514b02..4d45c0e 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"d3-force": "^3.0.0","date-fns": "^4.4.0","gray-matter": "^4.0.3",+ "jose": "^6.2.3","lucide-react": "^1.17.0","minisearch": "^7.1.2","next": "16.2.7",