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
feat: OAuth for the MCP endpoint (Claude.ai custom connectors)
Ronalds Palacis3ee418f846a8
diff --git a/DEPLOY.md b/DEPLOY.mdindex 6d2f036..562c683 100644--- a/DEPLOY.md+++ b/DEPLOY.md@@ -62,6 +62,15 @@ see the **active** vault:claude mcp add --transport http engram https://<your-app>.up.railway.app/api/mcp \--header "Authorization: Bearer <token from the Connect page>"```+Claude Code, Cursor, and Cline take that bearer header directly.++### Connect from Claude.ai (custom connector — OAuth)+Claude.ai's web connectors authenticate via **OAuth, not a pasted token**. Engram serves the+OAuth flow automatically **whenever `AUTH_SECRET` is set** (no extra config): Settings →+**Connectors** → **Add custom connector** → URL `https://<your-app>/api/mcp`. Claude registers+itself (Dynamic Client Registration) and sends you through **your Google login + email+allowlist**; approve and you're connected — no open endpoint, no shared secret. Requires a paid+Claude plan (and, on Team/Enterprise, an admin to enable custom connectors).## Notes- **No auth locally:** leave `AUTH_SECRET` empty (or `AUTH_DISABLED=true`) and the dashboard is open; the MCP is open until a token exists.diff --git a/app/api/auth/callback/route.ts b/app/api/auth/callback/route.tsindex 6e4301a..f976463 100644--- a/app/api/auth/callback/route.ts+++ b/app/api/auth/callback/route.ts@@ -31,8 +31,10 @@ export async function GET(req: Request) {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" : ""}`,- );+ const flag = secure ? "; Secure" : "";+ const next = cookies.auth_next && cookies.auth_next.startsWith("/") && !cookies.auth_next.startsWith("//") ? cookies.auth_next : "/";+ const headers = new Headers({ location: next });+ headers.append("set-cookie", `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${60 * 60 * 24 * 30}${flag}`);+ headers.append("set-cookie", `auth_next=; Path=/; Max-Age=0${flag}`);+ return new Response(null, { status: 302, headers });}diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.tsindex c8fe218..1143c26 100644--- a/app/api/auth/login/route.ts+++ b/app/api/auth/login/route.ts@@ -3,15 +3,17 @@ import { APP_URL, GOOGLE_CLIENT_ID } from "@/lib/config";export const dynamic = "force-dynamic";-export function GET() {+export function GET(req: Request) {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" : ""}`,- },- });+ const flag = secure ? "; Secure" : "";+ const headers = new Headers({ location: googleAuthUrl(state) });+ headers.append("set-cookie", `oauth_state=${state}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${flag}`);+ // Where to land after login (e.g. resume an OAuth /authorize flow). Same-origin paths only.+ const next = new URL(req.url).searchParams.get("next");+ if (next && next.startsWith("/") && !next.startsWith("//")) {+ headers.append("set-cookie", `auth_next=${encodeURIComponent(next)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${flag}`);+ }+ return new Response(null, { status: 302, headers });}diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.tsindex 038dc28..ed61ddf 100644--- a/app/api/mcp/route.ts+++ b/app/api/mcp/route.ts@@ -1,6 +1,7 @@import { MCP_TOKEN } from "@/lib/config";import { harnessEnabled } from "@/lib/settings";import { hasAnyToken, verifyToken } from "@/lib/tokens";+import { oauthEnabled, verifyAccessToken, wwwAuthenticate } from "@/lib/oauth";import { TOOLS, TOOL_MAP } from "@/lib/mcp/tools";export const dynamic = "force-dynamic";@@ -60,14 +61,28 @@ function jsonResponse(body: Json, status = 200) {return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });}+/** A credential is valid if it matches the shared token, a per-teammate token, or a live OAuth access token. */+async function authOk(token: string): Promise<boolean> {+ if (!token) return false;+ if (MCP_TOKEN !== "" && token === MCP_TOKEN) return true;+ if (verifyToken(token)) return true;+ if (oauthEnabled() && (await verifyAccessToken(token))) return true;+ return false;+}++/** 401 that also advertises the OAuth flow (WWW-Authenticate) so connectors can discover it. */+function unauthorized(): Response {+ const headers: Record<string, string> = { "content-type": "application/json" };+ if (oauthEnabled()) headers["WWW-Authenticate"] = wwwAuthenticate();+ return new Response(JSON.stringify(rpc(null, undefined, { code: -32001, message: "unauthorized" })), { status: 401, headers });+}+export async function POST(req: Request) {- // Enforce the bearer only when auth is configured (env MCP_TOKEN or any team token).- // Open locally when nothing is set.+ // Enforce auth when any is configured (env MCP_TOKEN, a team token, or OAuth). Open+ // locally when nothing is set. On failure, advertise OAuth so Claude.ai can connect.const token = (req.headers.get("authorization") || "").replace(/^Bearer\s+/i, "").trim();- if (MCP_TOKEN !== "" || hasAnyToken()) {- const ok = (MCP_TOKEN !== "" && token === MCP_TOKEN) || verifyToken(token);- if (!ok) return jsonResponse(rpc(null, undefined, { code: -32001, message: "unauthorized" }), 401);- }+ const authRequired = MCP_TOKEN !== "" || hasAnyToken() || oauthEnabled();+ if (authRequired && !(await authOk(token))) return unauthorized();let body: Json;try {@@ -84,7 +99,11 @@ export async function POST(req: Request) {return res ? jsonResponse(res) : new Response(null, { status: 202 });}-// This server is request/response only (no server-initiated SSE stream).+// This server is request/response only (no server-initiated SSE stream). When OAuth is on,+// answer probes with a 401 that advertises the flow so connectors can discover it.export function GET() {+ if (oauthEnabled()) {+ return new Response("Unauthorized", { status: 401, headers: { "WWW-Authenticate": wwwAuthenticate() } });+ }return new Response("Method Not Allowed", { status: 405 });}diff --git a/app/api/oauth/authorization-server/route.ts b/app/api/oauth/authorization-server/route.tsnew file mode 100644index 0000000..2d57a4e--- /dev/null+++ b/app/api/oauth/authorization-server/route.ts@@ -0,0 +1,10 @@+import { authServerMetadata, CORS } from "@/lib/oauth";++export const dynamic = "force-dynamic";++export function GET() {+ return Response.json(authServerMetadata(), { headers: CORS });+}+export function OPTIONS() {+ return new Response(null, { status: 204, headers: CORS });+}diff --git a/app/api/oauth/authorize/route.ts b/app/api/oauth/authorize/route.tsnew file mode 100644index 0000000..32b9063--- /dev/null+++ b/app/api/oauth/authorize/route.ts@@ -0,0 +1,69 @@+import { isAllowed, verifySessionToken } from "@/lib/auth";+import { SESSION_COOKIE } from "@/lib/config";+import { getClient, issueCode, oauthEnabled } from "@/lib/oauth";++export const dynamic = "force-dynamic";++function cookie(req: Request, name: string): string | undefined {+ for (const part of (req.headers.get("cookie") || "").split(";")) {+ const i = part.indexOf("=");+ if (i > -1 && part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim());+ }+ return undefined;+}+const redirect = (location: string) => new Response(null, { status: 302, headers: { location } });++/**+ * Authorization endpoint. Validates the client + PKCE, gates on Engram's Google session+ * (redirecting through login when needed), then issues a single-use code back to the client.+ */+export async function GET(req: Request) {+ if (!oauthEnabled()) return new Response("OAuth is not enabled on this instance.", { status: 404 });+ const url = new URL(req.url);+ const p = url.searchParams;+ const clientId = p.get("client_id") || "";+ const redirectUri = p.get("redirect_uri") || "";+ const responseType = p.get("response_type") || "";+ const codeChallenge = p.get("code_challenge") || "";+ const codeChallengeMethod = p.get("code_challenge_method") || "";+ const state = p.get("state") || "";+ const scope = p.get("scope") || "mcp";++ // Can't safely bounce errors to an unregistered redirect_uri, so validate it first.+ const client = getClient(clientId);+ if (!client || !client.redirect_uris.includes(redirectUri)) {+ return new Response("Invalid client_id or redirect_uri.", { status: 400 });+ }+ const errorBack = (code: string, desc?: string) => {+ const u = new URL(redirectUri);+ u.searchParams.set("error", code);+ if (desc) u.searchParams.set("error_description", desc);+ if (state) u.searchParams.set("state", state);+ return redirect(u.toString());+ };+ if (responseType !== "code") return errorBack("unsupported_response_type");+ if (!codeChallenge || (codeChallengeMethod && codeChallengeMethod !== "S256")) {+ return errorBack("invalid_request", "PKCE with S256 is required");+ }++ // Gate on the Engram session (same Google login + allowlist as the dashboard).+ const sess = cookie(req, SESSION_COOKIE);+ const user = sess ? await verifySessionToken(sess) : null;+ if (!user || !isAllowed(user.email)) {+ const next = url.pathname + url.search; // resume here after login+ return redirect(`/api/auth/login?next=${encodeURIComponent(next)}`);+ }++ const code = await issueCode({+ cid: clientId,+ redirect_uri: redirectUri,+ cc: codeChallenge,+ ccm: codeChallengeMethod || "S256",+ sub: user.email,+ scope,+ });+ const back = new URL(redirectUri);+ back.searchParams.set("code", code);+ if (state) back.searchParams.set("state", state);+ return redirect(back.toString());+}diff --git a/app/api/oauth/protected-resource/route.ts b/app/api/oauth/protected-resource/route.tsnew file mode 100644index 0000000..a525300--- /dev/null+++ b/app/api/oauth/protected-resource/route.ts@@ -0,0 +1,10 @@+import { CORS, protectedResourceMetadata } from "@/lib/oauth";++export const dynamic = "force-dynamic";++export function GET() {+ return Response.json(protectedResourceMetadata(), { headers: CORS });+}+export function OPTIONS() {+ return new Response(null, { status: 204, headers: CORS });+}diff --git a/app/api/oauth/register/route.ts b/app/api/oauth/register/route.tsnew file mode 100644index 0000000..5732027--- /dev/null+++ b/app/api/oauth/register/route.ts@@ -0,0 +1,34 @@+import { corsJson, CORS, oauthEnabled, registerClient } from "@/lib/oauth";++export const dynamic = "force-dynamic";++/** Dynamic Client Registration (RFC 7591). Public clients (PKCE, no secret). */+export async function POST(req: Request) {+ if (!oauthEnabled()) return corsJson({ error: "oauth_disabled" }, 404);+ let body: Record<string, unknown>;+ try {+ body = await req.json();+ } catch {+ return corsJson({ error: "invalid_client_metadata", error_description: "invalid JSON" }, 400);+ }+ const uris = Array.isArray(body.redirect_uris) ? body.redirect_uris.filter((u): u is string => typeof u === "string") : [];+ if (uris.length === 0) {+ return corsJson({ error: "invalid_redirect_uri", error_description: "redirect_uris is required" }, 400);+ }+ const c = registerClient(uris, typeof body.client_name === "string" ? body.client_name : undefined);+ return corsJson(+ {+ client_id: c.client_id,+ client_id_issued_at: Math.floor(Date.now() / 1000),+ redirect_uris: c.redirect_uris,+ token_endpoint_auth_method: "none",+ grant_types: ["authorization_code"],+ response_types: ["code"],+ client_name: c.client_name,+ },+ 201,+ );+}+export function OPTIONS() {+ return new Response(null, { status: 204, headers: CORS });+}diff --git a/app/api/oauth/token/route.ts b/app/api/oauth/token/route.tsnew file mode 100644index 0000000..22dc409--- /dev/null+++ b/app/api/oauth/token/route.ts@@ -0,0 +1,38 @@+import { corsJson, CORS, issueAccessToken, oauthEnabled, redeemCode, verifyPkce } from "@/lib/oauth";++export const dynamic = "force-dynamic";++/** Read form-encoded (OAuth default) or JSON token-request bodies. */+async function parseBody(req: Request): Promise<Record<string, string>> {+ const ct = req.headers.get("content-type") || "";+ if (ct.includes("application/json")) {+ try {+ const j = await req.json();+ return Object.fromEntries(Object.entries(j).map(([k, v]) => [k, String(v)]));+ } catch {+ return {};+ }+ }+ const params = new URLSearchParams(await req.text());+ return Object.fromEntries(params.entries());+}++/** Token endpoint — exchange an authorization code (+ PKCE verifier) for an access token. */+export async function POST(req: Request) {+ if (!oauthEnabled()) return corsJson({ error: "invalid_request" }, 404);+ const b = await parseBody(req);+ if (b.grant_type !== "authorization_code") return corsJson({ error: "unsupported_grant_type" }, 400);+ if (!b.code || !b.code_verifier) return corsJson({ error: "invalid_request", error_description: "code and code_verifier required" }, 400);++ const payload = await redeemCode(b.code);+ if (!payload) return corsJson({ error: "invalid_grant", error_description: "code invalid, expired, or already used" }, 400);+ if (b.client_id && b.client_id !== payload.cid) return corsJson({ error: "invalid_grant", error_description: "client mismatch" }, 400);+ if (b.redirect_uri && b.redirect_uri !== payload.redirect_uri) return corsJson({ error: "invalid_grant", error_description: "redirect_uri mismatch" }, 400);+ if (!verifyPkce(b.code_verifier, payload.cc, payload.ccm)) return corsJson({ error: "invalid_grant", error_description: "PKCE verification failed" }, 400);++ const { token, expiresIn } = await issueAccessToken(payload.sub, payload.scope);+ return corsJson({ access_token: token, token_type: "Bearer", expires_in: expiresIn, scope: payload.scope }, 200);+}+export function OPTIONS() {+ return new Response(null, { status: 204, headers: CORS });+}diff --git a/lib/oauth.ts b/lib/oauth.tsnew file mode 100644index 0000000..ae5565b--- /dev/null+++ b/lib/oauth.ts@@ -0,0 +1,165 @@+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { SignJWT, jwtVerify } from "jose";+import { APP_URL, AUTH_SECRET, DATA_ROOT } from "@/lib/config";++/**+ * Minimal OAuth 2.0 Authorization Server for the MCP endpoint, so OAuth-only clients+ * (Claude.ai custom connectors) can connect without a pasted bearer token. Implements the+ * MCP authorization flow: Dynamic Client Registration (RFC 7591) + Authorization Code with+ * PKCE (S256). The authorize step is gated by Engram's existing Google login + email+ * allowlist. Tokens are signed JWTs (jose/HS256, keyed off AUTH_SECRET) — no token store.+ * Enabled whenever AUTH_SECRET is set (i.e. a real deploy); off in open local dev.+ */++const STATE_DIR = process.env.ENGRAM_STATE_DIR || DATA_ROOT;+const CLIENTS_FILE = path.join(STATE_DIR, "oauth-clients.json");+const AUD = "engram-mcp";++const key = () => new TextEncoder().encode(AUTH_SECRET);+export function oauthEnabled(): boolean {+ return AUTH_SECRET !== "";+}+const ISSUER = () => APP_URL;+export const RESOURCE = () => `${APP_URL}/api/mcp`;++export const CORS: Record<string, string> = {+ "access-control-allow-origin": "*",+ "access-control-allow-methods": "GET, POST, OPTIONS",+ "access-control-allow-headers": "Content-Type, Authorization, mcp-protocol-version",+};+export function corsJson(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json", "cache-control": "no-store", ...CORS },+ });+}++// ── Dynamic Client Registration ──────────────────────────────────────────────+export interface OAuthClient {+ client_id: string;+ redirect_uris: string[];+ client_name?: string;+ created: string;+}+function loadClients(): OAuthClient[] {+ try {+ return JSON.parse(fs.readFileSync(CLIENTS_FILE, "utf8"));+ } catch {+ return [];+ }+}+function saveClients(c: OAuthClient[]) {+ fs.mkdirSync(STATE_DIR, { recursive: true });+ fs.writeFileSync(CLIENTS_FILE, JSON.stringify(c, null, 2));+}+export function registerClient(redirect_uris: string[], client_name?: string): OAuthClient {+ const rec: OAuthClient = { client_id: crypto.randomUUID(), redirect_uris, client_name, created: new Date().toISOString() };+ const all = loadClients();+ all.push(rec);+ saveClients(all);+ return rec;+}+export function getClient(id: string): OAuthClient | null {+ return loadClients().find((c) => c.client_id === id) ?? null;+}++// ── PKCE (S256 only) ─────────────────────────────────────────────────────────+export function verifyPkce(verifier: string, challenge: string, method?: string): boolean {+ if (method && method !== "S256") return false;+ if (!verifier || !challenge) return false;+ const h = crypto.createHash("sha256").update(verifier).digest("base64url");+ return crypto.timingSafeEqual(Buffer.from(h), Buffer.from(challenge));+}++// ── Authorization code (short-lived JWT, single-use) ─────────────────────────+export interface CodePayload {+ cid: string;+ redirect_uri: string;+ cc: string;+ ccm: string;+ sub: string;+ scope: string;+}+export async function issueCode(p: CodePayload): Promise<string> {+ return new SignJWT({ ...p, typ: "code" })+ .setProtectedHeader({ alg: "HS256" })+ .setIssuedAt()+ .setJti(crypto.randomUUID())+ .setExpirationTime("5m")+ .sign(key());+}+const usedCodes = new Set<string>();+export async function redeemCode(code: string): Promise<CodePayload | null> {+ try {+ const { payload } = await jwtVerify(code, key());+ if (payload.typ !== "code") return null;+ const jti = payload.jti as string;+ if (!jti || usedCodes.has(jti)) return null;+ usedCodes.add(jti);+ return {+ cid: payload.cid as string,+ redirect_uri: payload.redirect_uri as string,+ cc: payload.cc as string,+ ccm: (payload.ccm as string) || "S256",+ sub: payload.sub as string,+ scope: (payload.scope as string) ?? "",+ };+ } catch {+ return null;+ }+}++// ── Access token (JWT) ───────────────────────────────────────────────────────+export async function issueAccessToken(sub: string, scope: string): Promise<{ token: string; expiresIn: number }> {+ const expiresIn = 60 * 60 * 24 * 30; // 30 days+ const token = await new SignJWT({ scope, typ: "at" })+ .setProtectedHeader({ alg: "HS256" })+ .setSubject(sub)+ .setIssuer(ISSUER())+ .setAudience(AUD)+ .setIssuedAt()+ .setJti(crypto.randomUUID())+ .setExpirationTime("30d")+ .sign(key());+ return { token, expiresIn };+}+export async function verifyAccessToken(token: string): Promise<{ sub: string; scope: string } | null> {+ if (!token) return null;+ try {+ const { payload } = await jwtVerify(token, key(), { audience: AUD, issuer: ISSUER() });+ if (payload.typ !== "at") return null;+ return { sub: payload.sub as string, scope: (payload.scope as string) ?? "" };+ } catch {+ return null;+ }+}++// ── Discovery metadata ───────────────────────────────────────────────────────+export function protectedResourceMetadata() {+ return {+ resource: RESOURCE(),+ authorization_servers: [ISSUER()],+ bearer_methods_supported: ["header"],+ scopes_supported: ["mcp"],+ };+}+export function authServerMetadata() {+ const b = APP_URL;+ return {+ issuer: ISSUER(),+ authorization_endpoint: `${b}/api/oauth/authorize`,+ token_endpoint: `${b}/api/oauth/token`,+ registration_endpoint: `${b}/api/oauth/register`,+ response_types_supported: ["code"],+ grant_types_supported: ["authorization_code"],+ code_challenge_methods_supported: ["S256"],+ token_endpoint_auth_methods_supported: ["none"],+ scopes_supported: ["mcp"],+ };+}++export function wwwAuthenticate(): string {+ return `Bearer resource_metadata="${APP_URL}/.well-known/oauth-protected-resource"`;+}diff --git a/middleware.ts b/middleware.tsindex 9550cdf..54ce13e 100644--- a/middleware.ts+++ b/middleware.ts@@ -29,7 +29,7 @@ export async function middleware(req: NextRequest) {}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).*)"],+ // Protect everything except the MCP endpoint (bearer-token), health, the auth ++ // OAuth routes, the OAuth discovery well-knowns, the login page, and static assets.+ matcher: ["/((?!api/mcp|api/health|api/auth|api/oauth|\\.well-known|login|_next/static|_next/image|favicon.ico).*)"],};diff --git a/next.config.ts b/next.config.tsindex 84c08dd..c1d3e02 100644--- a/next.config.ts+++ b/next.config.ts@@ -8,6 +8,15 @@ const nextConfig: NextConfig = {// The vault (markdown, source of truth) lives outside the app dir and is read// at runtime via fs from VAULT_DIR — never bundled.serverExternalPackages: ["simple-git", "gray-matter", "chokidar"],+ // OAuth discovery lives at well-known paths; map them to the API routes.+ async rewrites() {+ return [+ { source: "/.well-known/oauth-protected-resource", destination: "/api/oauth/protected-resource" },+ { source: "/.well-known/oauth-protected-resource/:path*", destination: "/api/oauth/protected-resource" },+ { source: "/.well-known/oauth-authorization-server", destination: "/api/oauth/authorization-server" },+ { source: "/.well-known/oauth-authorization-server/:path*", destination: "/api/oauth/authorization-server" },+ ];+ },};export default nextConfig;