feat: Phase 1 — Authentik auth, MCP endpoint, persistent memory

End-to-end Phase 1 of shared-memory: a logged-in Authentik user can sign
into the Web UI (/me debug page), and an MCP client with an Authentik-
issued bearer token can call memory.write / memory.list / memory.get /
memory.delete plus project.identify against /api/mcp.

Stack:
- Next.js 15 (App Router) + React 19 + TypeScript, pnpm workspaces
- Drizzle ORM + Postgres 16 + pgvector + pg_trgm
- Auth.js v5 with Authentik provider (Web UI)
- jose + Authentik JWKS for MCP bearer-token validation
- JSON-RPC 2.0 dispatcher implementing the MCP wire protocol over plain
  HTTP POST (hand-rolled to fit Next.js App Router; switches to SSE in a
  later phase if server-initiated events are needed)
- bge-small embeddings sidecar deferred to Phase 2; the schema already
  reserves the vector(384) column + IVFFlat index, FTS via a STORED
  tsvector column, and the visibility enum (private/shared/team) so
  cross-user memory sharing can be added without a future migration

Deployment supports two modes (set in .env, never committed):
- Behind an external reverse proxy (HAProxy / nginx / Cloudflare Tunnel /
  Traefik) — DEFAULT; the app exposes APP_PORT on the host with
  X-Forwarded-* trusted, no in-container TLS
- Built-in TLS via Caddy — opt-in with `docker compose --profile tls up`

Discovery endpoint at /.well-known/oauth-protected-resource (RFC 9728)
points MCP clients at the Authentik authorization server after a 401.

README walks through both Authentik providers (Web UI + MCP resource
server), the audience scope mapping, redirect URIs, and includes a worked
HAProxy config snippet.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-15 07:04:11 -07:00
co-authored by Claude Opus 4.7
parent d5be753cfb
commit 077d0a0825
37 changed files with 7294 additions and 8 deletions
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { env } from "@/lib/env";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* RFC 9728 — OAuth 2.0 Protected Resource Metadata.
*
* MCP clients discover the authorization server (Authentik) via this
* endpoint after receiving a 401 with `WWW-Authenticate: resource_metadata=...`.
*/
export function GET() {
const resource = env().PUBLIC_URL.replace(/\/$/, "");
return NextResponse.json({
resource,
authorization_servers: [env().OIDC_ISSUER],
scopes_supported: ["openid", "profile", "email"],
bearer_methods_supported: ["header"],
resource_documentation: `${resource}/`,
});
}
@@ -0,0 +1,2 @@
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { pg } from "@/lib/db/client";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Liveness + DB connectivity probe for the docker healthcheck.
* Returns 200 only if Postgres responds within the request timeout.
*/
export async function GET() {
try {
await pg`SELECT 1`;
return NextResponse.json({ status: "ok", db: "up" });
} catch (e) {
return NextResponse.json(
{ status: "degraded", db: "down", error: e instanceof Error ? e.message : "unknown" },
{ status: 503 },
);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { NextResponse } from "next/server";
import { authenticateBearer, UnauthorizedError } from "@/lib/auth/jwt";
import { userContextFromClaims } from "@/lib/mcp/context";
import { dispatchMcpMessage } from "@/lib/mcp/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* MCP streamable-HTTP endpoint.
*
* Auth: Bearer token (Authentik-issued JWT). Unauthed requests get 401 with
* a WWW-Authenticate header pointing at our RFC 9728 resource metadata
* so MCP clients can discover the authorization server.
*
* Body: JSON-RPC 2.0 message (request or notification).
*
* Reply: For requests, the JSON-RPC response in the body with
* `Content-Type: application/json`.
* For notifications, HTTP 202 with empty body.
*/
export async function POST(req: Request) {
// ---- auth ----
let claims;
try {
claims = await authenticateBearer(req.headers.get("authorization"));
} catch (e) {
if (e instanceof UnauthorizedError) {
return new NextResponse(JSON.stringify({ error: e.reason }), {
status: 401,
headers: {
"WWW-Authenticate": e.wwwAuthenticate,
"Content-Type": "application/json",
},
});
}
throw e;
}
// ---- parse body ----
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json(
{ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } },
{ status: 400 },
);
}
// ---- resolve user, dispatch ----
const ctx = await userContextFromClaims(claims);
// MCP supports batched requests (array) and single. Handle both.
if (Array.isArray(body)) {
const responses = await Promise.all(body.map((m) => dispatchMcpMessage(m, ctx)));
const filtered = responses.filter((r) => r !== null);
if (filtered.length === 0) {
return new NextResponse(null, { status: 202 });
}
return NextResponse.json(filtered, { status: 200 });
}
const response = await dispatchMcpMessage(body, ctx);
if (response === null) {
// Notification — no body expected.
return new NextResponse(null, { status: 202 });
}
return NextResponse.json(response, { status: 200 });
}
// MCP clients sometimes probe with GET (for SSE). We don't support
// server-initiated events in Phase 1 — return 405 with a discoverable header.
export function GET() {
return new NextResponse(null, {
status: 405,
headers: { Allow: "POST" },
});
}
+71
View File
@@ -0,0 +1,71 @@
:root {
color-scheme: light dark;
--bg: #0b0d10;
--fg: #e7e9ec;
--muted: #8a9099;
--accent: #6ea8fe;
--surface: #14181d;
--border: #232a31;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
min-height: 100%;
background: var(--bg);
color: var(--fg);
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 15px;
line-height: 1.55;
}
a {
color: var(--accent);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
button {
font: inherit;
color: var(--fg);
background: var(--surface);
border: 1px solid var(--border);
padding: 0.5rem 0.9rem;
border-radius: 0.375rem;
cursor: pointer;
}
button:hover {
border-color: var(--accent);
}
pre {
background: var(--surface);
border: 1px solid var(--border);
padding: 1rem;
border-radius: 0.5rem;
overflow-x: auto;
font-size: 13px;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.container {
max-width: 880px;
margin: 0 auto;
padding: 2rem 1.25rem;
}
.muted {
color: var(--muted);
}
+16
View File
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import type { ReactNode } from "react";
import "./globals.css";
export const metadata: Metadata = {
title: "shared-memory",
description: "Shared persistent memory for Claude Code sessions",
};
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
+31
View File
@@ -0,0 +1,31 @@
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
export const dynamic = "force-dynamic";
export default async function MePage() {
const session = await auth();
if (!session?.user) {
redirect("/api/auth/signin");
}
return (
<main className="container">
<h1>Signed in</h1>
<p className="muted">
Debug view confirms the Authentik round-trip and the OIDC claims we
received.
</p>
<h2>Session</h2>
<pre>{JSON.stringify(session, null, 2)}</pre>
<form
action={async () => {
"use server";
await signOut({ redirectTo: "/" });
}}
>
<button type="submit">Sign out</button>
</form>
</main>
);
}
+35
View File
@@ -0,0 +1,35 @@
import Link from "next/link";
import { auth } from "@/auth";
export const dynamic = "force-dynamic";
export default async function HomePage() {
const session = await auth();
return (
<main className="container">
<h1>shared-memory</h1>
<p className="muted">
Self-hosted MCP server providing shared persistent memory across Claude Code sessions.
</p>
{session?.user ? (
<p>
Signed in as <strong>{session.user.email ?? session.user.name ?? session.user.id}</strong>{" "}
<Link href="/me">view session</Link>
</p>
) : (
<p>
<Link href="/api/auth/signin">Sign in with Authentik</Link>
</p>
)}
<hr style={{ borderColor: "var(--border)", margin: "2rem 0" }} />
<h2>MCP endpoint</h2>
<p className="muted">
Connect a Claude Code session to <code>/api/mcp</code> with a bearer token
issued by Authentik for this resource. See the README for setup steps.
</p>
</main>
);
}