feat: Phase 3b — proper Web UI for memories, projects, settings

Replaces the debug /me + /connect pages with a real authed app shell.

Pages
- /                       — anonymous landing; redirects to /dashboard once signed in
- /dashboard              — recent memories + top projects, quick "new memory" action
- /memories               — searchable list with hybrid (vector+FTS+tags) scoring;
                            per-result rank breakdown shown inline
- /memories/[id]          — view + inline edit toggle + delete
- /memories/new           — create form with project autocomplete
- /projects               — list with memory counts and last-activity
- /projects/[key]         — that project's memories
- /settings               — read-only Authentik profile + link to tokens
- /settings/tokens        — list / create / revoke CLI tokens

Old URLs preserved as redirects:
- /me      → /dashboard
- /connect → /settings/tokens

Stack additions
- Tailwind v4 with CSS-first @theme tokens (dark only for now)
- App shell in app/(authed)/ — auth guard + top nav with global search box
- Lightweight UI primitives in app/_components/ui/ (Button, Input, Card,
  Badge, EmptyState, Container, PageHeader)
- Search logic extracted from MCP tool into lib/memories.ts so Web UI and
  MCP both call the same RRF code path
- Memory CRUD via Server Actions in lib/memory-actions.ts; audit_log
  rows are tagged actor='web' to distinguish from MCP writes

Per-token revoke
- New cli_tokens table (id, user_id, jti unique, name, created_at,
  last_used_at, expires_at, revoked_at) — migration 0001_cli_tokens.sql
- mintCliToken now records jti + name; verifyCliToken enforces revocation
  for tracked tokens. Legacy tokens minted before this change (no jti)
  are accepted on signature alone until they expire naturally.
- /settings/tokens lists active + revoked tokens with one-click revoke

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-15 10:57:17 -07:00
co-authored by Claude Opus 4.7
parent 609039f098
commit ff6baab393
33 changed files with 2475 additions and 395 deletions
+44
View File
@@ -0,0 +1,44 @@
import Link from "next/link";
import { Container } from "@/app/_components/ui/container";
import { UserMenu } from "./_user-menu";
import { SearchBox } from "./_search-box";
import type { Session } from "next-auth";
export function Nav({ user }: { user: Session["user"] }) {
return (
<header className="fixed top-0 inset-x-0 z-20 h-14 bg-surface-1/80 backdrop-blur border-b border-border">
<Container className="h-full flex items-center gap-4">
<Link
href="/memories"
className="flex items-center gap-2 text-fg font-semibold tracking-tight no-underline"
>
<span className="inline-block size-2 rounded-full bg-accent-400" />
shared-memory
</Link>
<nav className="hidden md:flex items-center gap-1 ml-2">
<NavLink href="/memories">Memories</NavLink>
<NavLink href="/projects">Projects</NavLink>
<NavLink href="/settings">Settings</NavLink>
</nav>
<div className="flex-1 max-w-md ml-auto">
<SearchBox />
</div>
<UserMenu user={user} />
</Container>
</header>
);
}
function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
return (
<Link
href={href}
className="px-2.5 py-1.5 rounded-md text-sm text-fg-muted hover:text-fg hover:bg-surface-2 no-underline"
>
{children}
</Link>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { Input } from "@/app/_components/ui/input";
/**
* Global search — submits a GET to /memories with `?q=`. Server-rendered
* results page handles the actual memory.search call.
*/
export function SearchBox() {
return (
<form action="/memories" method="GET" role="search">
<Input
type="search"
name="q"
placeholder="Search memories…"
aria-label="Search memories"
autoComplete="off"
/>
</form>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { signOut } from "@/auth";
import { Button } from "@/app/_components/ui/button";
import type { Session } from "next-auth";
async function signOutAction() {
"use server";
await signOut({ redirectTo: "/" });
}
export function UserMenu({ user }: { user: Session["user"] }) {
const label = user.email ?? user.name ?? user.id;
// Compact, single-line label; truncate on small screens via Tailwind.
return (
<div className="flex items-center gap-2">
<span
className="hidden sm:inline-block text-xs text-fg-muted max-w-[160px] truncate"
title={label}
>
{label}
</span>
<form action={signOutAction}>
<Button type="submit" variant="secondary" size="sm">
Sign out
</Button>
</form>
</div>
);
}
+154
View File
@@ -0,0 +1,154 @@
import Link from "next/link";
import { and, desc, eq, isNull, sql, count } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody, CardHeader } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge";
import { Button } from "@/app/_components/ui/button";
import { EmptyState } from "@/app/_components/ui/empty-state";
export const dynamic = "force-dynamic";
export default async function DashboardPage() {
const session = await auth();
const userId = session!.user.id;
const [counts, recent, topProjects] = await Promise.all([
db
.select({
total: count(memories.id),
})
.from(memories)
.where(and(eq(memories.userId, userId), isNull(memories.deletedAt))),
db
.select({
id: memories.id,
content: memories.content,
scope: memories.scope,
tags: memories.tags,
createdAt: memories.createdAt,
projectKey: projects.key,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(and(eq(memories.userId, userId), isNull(memories.deletedAt)))
.orderBy(desc(memories.createdAt))
.limit(5),
db
.select({
id: projects.id,
key: projects.key,
displayName: projects.displayName,
memoryCount: sql<number>`count(${memories.id})::int`,
})
.from(projects)
.leftJoin(
memories,
and(eq(memories.projectId, projects.id), isNull(memories.deletedAt)),
)
.where(eq(projects.userId, userId))
.groupBy(projects.id)
.orderBy(desc(sql`count(${memories.id})`))
.limit(4),
]);
const memoryTotal = counts[0]?.total ?? 0;
return (
<Container className="pt-6">
<PageHeader
title={`Welcome, ${session!.user.name ?? session!.user.email ?? "there"}`}
description={`${memoryTotal} memor${memoryTotal === 1 ? "y" : "ies"} across ${topProjects.length} project${topProjects.length === 1 ? "" : "s"}.`}
actions={
<Link href="/memories/new" className="no-underline">
<Button>New memory</Button>
</Link>
}
/>
<div className="grid gap-6 md:grid-cols-3">
<section className="md:col-span-2 space-y-2">
<h2 className="text-sm font-medium text-fg-muted mb-2">Recent</h2>
{recent.length === 0 ? (
<EmptyState
title="No memories yet"
description="Write one from the MCP, or create one here."
action={
<Link href="/memories/new" className="no-underline">
<Button>Create the first one</Button>
</Link>
}
/>
) : (
recent.map((m) => (
<Link
key={m.id}
href={`/memories/${m.id}`}
className="block no-underline"
>
<Card className="hover:border-border-strong transition-colors">
<CardBody className="space-y-2">
<div className="flex items-center gap-2 text-xs text-fg-subtle">
<Badge tone={m.scope === "user" ? "accent" : "neutral"}>
{m.scope}
</Badge>
{m.projectKey ? <span>· {m.projectKey}</span> : null}
<span className="ml-auto">
{new Date(m.createdAt).toLocaleDateString()}
</span>
</div>
<p className="text-sm text-fg line-clamp-2">{m.content}</p>
{m.tags.length ? (
<div className="flex gap-1 flex-wrap">
{m.tags.slice(0, 6).map((t) => (
<Badge key={t}>{t}</Badge>
))}
</div>
) : null}
</CardBody>
</Card>
</Link>
))
)}
</section>
<section>
<h2 className="text-sm font-medium text-fg-muted mb-2">Projects</h2>
{topProjects.length === 0 ? (
<p className="text-sm text-fg-subtle">No projects yet.</p>
) : (
<Card>
{topProjects.map((p, i) => (
<Link
key={p.id}
href={`/projects/${encodeURIComponent(p.key)}`}
className={`block px-4 py-3 hover:bg-surface-2 no-underline ${i > 0 ? "border-t border-border" : ""}`}
>
<div className="flex items-center gap-2">
<span className="font-mono text-sm text-fg truncate">
{p.key}
</span>
<Badge className="ml-auto">{p.memoryCount}</Badge>
</div>
{p.displayName && p.displayName !== p.key ? (
<span className="block text-xs text-fg-muted truncate">
{p.displayName}
</span>
) : null}
</Link>
))}
<Link
href="/projects"
className="block px-4 py-2 text-xs text-fg-muted border-t border-border hover:bg-surface-2 no-underline"
>
All projects
</Link>
</Card>
)}
</section>
</div>
</Container>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { auth } from "@/auth";
import { Nav } from "./_nav";
export const dynamic = "force-dynamic";
export default async function AuthedLayout({ children }: { children: ReactNode }) {
const session = await auth();
if (!session?.user) {
redirect("/api/auth/signin?callbackUrl=/memories");
}
return (
<>
<Nav user={session.user} />
<div className="pt-16 pb-16">{children}</div>
</>
);
}
@@ -0,0 +1,142 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, eq, isNull } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
import { updateMemoryAction, deleteMemoryAction } from "@/lib/memory-actions";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody, CardHeader } from "@/app/_components/ui/card";
import { Input, Textarea, Label } from "@/app/_components/ui/input";
import { Button } from "@/app/_components/ui/button";
import { Badge } from "@/app/_components/ui/badge";
export const dynamic = "force-dynamic";
export default async function MemoryDetailPage({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ edit?: string }>;
}) {
const session = await auth();
const userId = session!.user.id;
const { id } = await params;
const { edit } = await searchParams;
const rows = await db
.select({
id: memories.id,
scope: memories.scope,
content: memories.content,
tags: memories.tags,
createdAt: memories.createdAt,
updatedAt: memories.updatedAt,
projectKey: projects.key,
projectId: memories.projectId,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(
and(eq(memories.id, id), eq(memories.userId, userId), isNull(memories.deletedAt)),
)
.limit(1);
const m = rows[0];
if (!m) notFound();
const isEditing = edit === "1";
return (
<Container className="pt-6 max-w-3xl">
<PageHeader
title={isEditing ? "Edit memory" : "Memory"}
description={<span className="font-mono text-xs text-fg-subtle">{m.id}</span>}
actions={
<>
<Link href="/memories" className="no-underline">
<Button type="button" variant="secondary">Back</Button>
</Link>
{!isEditing ? (
<Link href={`/memories/${m.id}?edit=1`} className="no-underline">
<Button>Edit</Button>
</Link>
) : null}
</>
}
/>
<Card className="mb-4">
<CardHeader className="flex items-center gap-2 text-xs text-fg-muted">
<Badge tone={m.scope === "user" ? "accent" : "neutral"}>{m.scope}</Badge>
{m.projectKey ? <span className="font-mono">{m.projectKey}</span> : null}
<span>· Created {new Date(m.createdAt).toLocaleString()}</span>
{m.updatedAt.getTime() !== m.createdAt.getTime() ? (
<span>· Updated {new Date(m.updatedAt).toLocaleString()}</span>
) : null}
</CardHeader>
{isEditing ? (
<CardBody>
<form action={updateMemoryAction} className="space-y-4">
<input type="hidden" name="id" value={m.id} />
<div>
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
name="content"
required
rows={12}
defaultValue={m.content}
className="mt-1"
/>
</div>
<div>
<Label htmlFor="tags" hint="comma- or space-separated">Tags</Label>
<Input
id="tags"
name="tags"
defaultValue={m.tags.join(", ")}
className="mt-1"
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<Link href={`/memories/${m.id}`} className="no-underline">
<Button type="button" variant="secondary">Cancel</Button>
</Link>
<Button type="submit">Save changes</Button>
</div>
</form>
</CardBody>
) : (
<CardBody>
<pre className="whitespace-pre-wrap break-words bg-transparent border-0 p-0 text-sm text-fg leading-relaxed">
{m.content}
</pre>
{m.tags.length ? (
<div className="flex gap-1 flex-wrap mt-4">
{m.tags.map((t) => (
<Badge key={t}>{t}</Badge>
))}
</div>
) : null}
</CardBody>
)}
</Card>
{!isEditing ? (
<form
action={deleteMemoryAction}
onSubmit={() => undefined}
className="flex justify-end"
>
<input type="hidden" name="id" value={m.id} />
<Button type="submit" variant="danger" size="sm">
Delete memory
</Button>
</form>
) : null}
</Container>
);
}
+108
View File
@@ -0,0 +1,108 @@
import Link from "next/link";
import { desc, eq } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { projects } from "@/lib/db/schema";
import { createMemoryAction } from "@/lib/memory-actions";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody } from "@/app/_components/ui/card";
import { Input, Textarea, Label } from "@/app/_components/ui/input";
import { Button } from "@/app/_components/ui/button";
export const dynamic = "force-dynamic";
export default async function NewMemoryPage({
searchParams,
}: {
searchParams: Promise<{ project?: string; scope?: string }>;
}) {
const session = await auth();
const userId = session!.user.id;
const params = await searchParams;
const initialProject = params.project ?? "";
const initialScope = params.scope === "user" ? "user" : "project";
const projectList = await db
.select({ key: projects.key, displayName: projects.displayName })
.from(projects)
.where(eq(projects.userId, userId))
.orderBy(desc(projects.updatedAt))
.limit(50);
return (
<Container className="pt-6 max-w-2xl">
<PageHeader
title="New memory"
description="Pick a scope, write content, optionally add tags."
/>
<Card>
<CardBody>
<form action={createMemoryAction} className="space-y-4">
<div>
<Label htmlFor="scope">Scope</Label>
<select
id="scope"
name="scope"
defaultValue={initialScope}
className="mt-1 h-9 px-2 rounded-md bg-surface-1 border border-border text-fg text-sm w-full"
>
<option value="project">Project attached to a project</option>
<option value="user">User global across all projects</option>
</select>
</div>
<div>
<Label htmlFor="project" hint="Required for project scope">
Project key
</Label>
<Input
id="project"
name="project"
defaultValue={initialProject}
placeholder="repo name, slug, or any stable string"
list="project-list"
className="mt-1"
/>
{projectList.length > 0 ? (
<datalist id="project-list">
{projectList.map((p) => (
<option key={p.key} value={p.key}>
{p.displayName ?? p.key}
</option>
))}
</datalist>
) : null}
</div>
<div>
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
name="content"
required
rows={10}
placeholder="What should the next session know?"
className="mt-1"
/>
</div>
<div>
<Label htmlFor="tags" hint="comma- or space-separated">
Tags
</Label>
<Input id="tags" name="tags" placeholder="auth, deployment, …" className="mt-1" />
</div>
<div className="flex justify-end gap-2 pt-2">
<Link href="/memories" className="no-underline">
<Button type="button" variant="secondary">Cancel</Button>
</Link>
<Button type="submit">Save memory</Button>
</div>
</form>
</CardBody>
</Card>
</Container>
);
}
+228
View File
@@ -0,0 +1,228 @@
import Link from "next/link";
import { and, desc, eq, isNull, inArray, sql } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
import { searchMemories } from "@/lib/memories";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge";
import { Button } from "@/app/_components/ui/button";
import { Input } from "@/app/_components/ui/input";
import { EmptyState } from "@/app/_components/ui/empty-state";
export const dynamic = "force-dynamic";
type Scope = "project" | "user";
interface MemoryRow {
id: string;
scope: "project" | "user";
projectKey: string | null;
content: string;
tags: string[];
createdAt: Date;
rank?: { rrfScore: number; vectorRank: number | null; ftsRank: number | null; tagRank: number | null };
}
async function fetchMemoriesByIds(
userId: string,
ids: string[],
): Promise<Map<string, MemoryRow>> {
if (ids.length === 0) return new Map();
const rows = await db
.select({
id: memories.id,
scope: memories.scope,
content: memories.content,
tags: memories.tags,
createdAt: memories.createdAt,
projectKey: projects.key,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(and(eq(memories.userId, userId), inArray(memories.id, ids), isNull(memories.deletedAt)));
return new Map(rows.map((r) => [r.id, r as MemoryRow]));
}
async function listRecent(userId: string, scope?: Scope, project?: string): Promise<MemoryRow[]> {
const filters = [eq(memories.userId, userId), isNull(memories.deletedAt)];
if (scope) filters.push(eq(memories.scope, scope));
if (project) {
filters.push(
sql`${memories.projectId} = (
SELECT id FROM ${projects}
WHERE ${projects.userId} = ${userId} AND ${projects.key} = ${project}
)`,
);
}
const rows = await db
.select({
id: memories.id,
scope: memories.scope,
content: memories.content,
tags: memories.tags,
createdAt: memories.createdAt,
projectKey: projects.key,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(and(...filters))
.orderBy(desc(memories.createdAt))
.limit(50);
return rows;
}
export default async function MemoriesPage({
searchParams,
}: {
searchParams: Promise<{ q?: string; scope?: string; project?: string }>;
}) {
const session = await auth();
const userId = session!.user.id;
const params = await searchParams;
const q = params.q?.trim() || undefined;
const scope = params.scope === "user" || params.scope === "project" ? params.scope : undefined;
const project = params.project?.trim() || undefined;
let rows: MemoryRow[] = [];
let debug: { vec: number; fts: number; tag: number } | null = null;
if (q) {
const result = await searchMemories(userId, q, { scope, projectKey: project }, 30);
const ids = result.hits.map((h) => h.id);
const byId = await fetchMemoriesByIds(userId, ids);
rows = result.hits.flatMap((h) => {
const r = byId.get(h.id);
return r ? [{ ...r, rank: h.rank }] : [];
});
debug = result.debug;
} else {
rows = await listRecent(userId, scope, project);
}
return (
<Container className="pt-6">
<PageHeader
title="Memories"
description={
q
? `${rows.length} result${rows.length === 1 ? "" : "s"} for "${q}"`
: "Most recent first."
}
actions={
<Link href="/memories/new" className="no-underline">
<Button>New memory</Button>
</Link>
}
/>
<form
method="GET"
action="/memories"
className="mb-6 flex flex-wrap items-center gap-2"
>
<Input
name="q"
placeholder="Search…"
defaultValue={q ?? ""}
aria-label="Search query"
className="flex-1 min-w-[200px]"
/>
<FilterSelect name="scope" value={scope} options={["", "project", "user"]} placeholder="Any scope" />
<Input
name="project"
placeholder="Project key…"
defaultValue={project ?? ""}
className="w-44"
/>
<Button type="submit" variant="secondary">Apply</Button>
</form>
{debug ? (
<p className="text-xs text-fg-subtle mb-3">
candidates · vector: {debug.vec} · fts: {debug.fts} · tag: {debug.tag}
</p>
) : null}
{rows.length === 0 ? (
<EmptyState
title={q ? "Nothing matched" : "No memories yet"}
description={q ? "Try a different query or remove filters." : "Create one or write via the MCP."}
action={
!q ? (
<Link href="/memories/new" className="no-underline">
<Button>Create the first one</Button>
</Link>
) : null
}
/>
) : (
<ul className="space-y-2">
{rows.map((m) => (
<li key={m.id}>
<Link href={`/memories/${m.id}`} className="block no-underline">
<Card className="hover:border-border-strong transition-colors">
<CardBody className="space-y-2">
<div className="flex items-center gap-2 text-xs text-fg-subtle flex-wrap">
<Badge tone={m.scope === "user" ? "accent" : "neutral"}>
{m.scope}
</Badge>
{m.projectKey ? (
<span className="font-mono">· {m.projectKey}</span>
) : null}
<span>·</span>
<span>{new Date(m.createdAt).toLocaleString()}</span>
{m.rank ? (
<span className="ml-auto text-fg-subtle">
rrf {m.rank.rrfScore.toFixed(4)} · v
{m.rank.vectorRank ?? ""} · f
{m.rank.ftsRank ?? ""} · t
{m.rank.tagRank ?? ""}
</span>
) : null}
</div>
<p className="text-sm text-fg line-clamp-3">{m.content}</p>
{m.tags.length ? (
<div className="flex gap-1 flex-wrap">
{m.tags.map((t) => (
<Badge key={t}>{t}</Badge>
))}
</div>
) : null}
</CardBody>
</Card>
</Link>
</li>
))}
</ul>
)}
</Container>
);
}
function FilterSelect({
name,
value,
options,
placeholder,
}: {
name: string;
value: string | undefined;
options: string[];
placeholder: string;
}) {
return (
<select
name={name}
defaultValue={value ?? ""}
className="h-9 px-2 rounded-md bg-surface-1 border border-border text-fg text-sm"
>
{options.map((o) => (
<option key={o} value={o}>
{o === "" ? placeholder : o}
</option>
))}
</select>
);
}
@@ -0,0 +1,121 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, desc, eq, isNull } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge";
import { Button } from "@/app/_components/ui/button";
import { EmptyState } from "@/app/_components/ui/empty-state";
export const dynamic = "force-dynamic";
export default async function ProjectDetailPage({
params,
}: {
params: Promise<{ key: string }>;
}) {
const session = await auth();
const userId = session!.user.id;
const { key: rawKey } = await params;
const key = decodeURIComponent(rawKey);
const projectRow = await db
.select()
.from(projects)
.where(and(eq(projects.userId, userId), eq(projects.key, key)))
.limit(1);
const project = projectRow[0];
if (!project) notFound();
const mem = await db
.select({
id: memories.id,
scope: memories.scope,
content: memories.content,
tags: memories.tags,
createdAt: memories.createdAt,
})
.from(memories)
.where(
and(
eq(memories.userId, userId),
eq(memories.projectId, project.id),
isNull(memories.deletedAt),
),
)
.orderBy(desc(memories.createdAt))
.limit(100);
return (
<Container className="pt-6">
<PageHeader
title={project.displayName ?? project.key}
description={
<>
<span className="font-mono">{project.key}</span>
{" · "}
{mem.length} memor{mem.length === 1 ? "y" : "ies"}
</>
}
actions={
<>
<Link href="/projects" className="no-underline">
<Button type="button" variant="secondary">All projects</Button>
</Link>
<Link
href={`/memories/new?project=${encodeURIComponent(project.key)}`}
className="no-underline"
>
<Button>New in this project</Button>
</Link>
</>
}
/>
{mem.length === 0 ? (
<EmptyState
title="No memories in this project yet"
description="Use the MCP from a Claude Code session, or create one here."
action={
<Link
href={`/memories/new?project=${encodeURIComponent(project.key)}`}
className="no-underline"
>
<Button>Create the first one</Button>
</Link>
}
/>
) : (
<ul className="space-y-2">
{mem.map((m) => (
<li key={m.id}>
<Link href={`/memories/${m.id}`} className="block no-underline">
<Card className="hover:border-border-strong transition-colors">
<CardBody className="space-y-2">
<div className="flex items-center gap-2 text-xs text-fg-subtle">
<Badge tone={m.scope === "user" ? "accent" : "neutral"}>
{m.scope}
</Badge>
<span>{new Date(m.createdAt).toLocaleString()}</span>
</div>
<p className="text-sm text-fg line-clamp-3">{m.content}</p>
{m.tags.length ? (
<div className="flex gap-1 flex-wrap">
{m.tags.map((t) => (
<Badge key={t}>{t}</Badge>
))}
</div>
) : null}
</CardBody>
</Card>
</Link>
</li>
))}
</ul>
)}
</Container>
);
}
+77
View File
@@ -0,0 +1,77 @@
import Link from "next/link";
import { and, desc, eq, isNull, sql } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge";
import { EmptyState } from "@/app/_components/ui/empty-state";
export const dynamic = "force-dynamic";
export default async function ProjectsPage() {
const session = await auth();
const userId = session!.user.id;
const rows = await db
.select({
id: projects.id,
key: projects.key,
displayName: projects.displayName,
createdAt: projects.createdAt,
memoryCount: sql<number>`count(${memories.id})::int`,
lastActivity: sql<Date | null>`max(${memories.createdAt})`,
})
.from(projects)
.leftJoin(
memories,
and(eq(memories.projectId, projects.id), isNull(memories.deletedAt)),
)
.where(eq(projects.userId, userId))
.groupBy(projects.id)
.orderBy(desc(sql`max(${memories.createdAt})`));
return (
<Container className="pt-6">
<PageHeader
title="Projects"
description={`${rows.length} project${rows.length === 1 ? "" : "s"}.`}
/>
{rows.length === 0 ? (
<EmptyState
title="No projects yet"
description="Projects are created automatically the first time you write a project-scoped memory or call project.identify from the MCP."
/>
) : (
<Card>
{rows.map((p, i) => (
<Link
key={p.id}
href={`/projects/${encodeURIComponent(p.key)}`}
className={`block px-4 py-3 hover:bg-surface-2 no-underline ${i > 0 ? "border-t border-border" : ""}`}
>
<div className="flex items-center gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-mono text-sm text-fg truncate">{p.key}</span>
<Badge>{p.memoryCount}</Badge>
</div>
{p.displayName && p.displayName !== p.key ? (
<div className="text-xs text-fg-muted truncate mt-0.5">{p.displayName}</div>
) : null}
</div>
<div className="text-xs text-fg-subtle whitespace-nowrap">
{p.lastActivity
? `last write ${new Date(p.lastActivity).toLocaleDateString()}`
: "empty"}
</div>
</div>
</Link>
))}
</Card>
)}
</Container>
);
}
+78
View File
@@ -0,0 +1,78 @@
import Link from "next/link";
import { eq } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody, CardHeader } from "@/app/_components/ui/card";
import { Button } from "@/app/_components/ui/button";
export const dynamic = "force-dynamic";
export default async function SettingsPage() {
const session = await auth();
const userId = session!.user.id;
const userRow = await db
.select()
.from(users)
.where(eq(users.id, userId))
.limit(1);
const user = userRow[0];
return (
<Container className="pt-6 max-w-3xl">
<PageHeader title="Settings" />
<div className="space-y-6">
<Card>
<CardHeader className="text-sm font-medium text-fg">Profile</CardHeader>
<CardBody className="space-y-2 text-sm">
<Field label="Name" value={user?.name} />
<Field label="Email" value={user?.email} />
<Field label="Internal user id" value={user?.id} mono />
<Field label="OIDC issuer" value={user?.oidcIss} mono />
<Field label="OIDC sub" value={user?.oidcSub} mono />
<Field
label="Joined"
value={user?.createdAt ? new Date(user.createdAt).toLocaleString() : null}
/>
</CardBody>
</Card>
<Card>
<CardHeader className="flex items-center">
<span className="text-sm font-medium text-fg flex-1">CLI tokens</span>
<Link href="/settings/tokens" className="no-underline">
<Button variant="secondary" size="sm">Manage tokens</Button>
</Link>
</CardHeader>
<CardBody className="text-sm text-fg-muted">
Bearer tokens for headless/automated MCP clients. Visit{" "}
<Link href="/settings/tokens">/settings/tokens</Link> to generate
and revoke them.
</CardBody>
</Card>
</div>
</Container>
);
}
function Field({
label,
value,
mono,
}: {
label: string;
value: string | null | undefined;
mono?: boolean;
}) {
return (
<div className="flex items-baseline gap-3">
<span className="text-fg-muted w-36 shrink-0">{label}</span>
<span className={`${mono ? "font-mono text-xs" : "text-sm"} text-fg break-all`}>
{value ?? <span className="text-fg-subtle"></span>}
</span>
</div>
);
}
@@ -0,0 +1,162 @@
import { revalidatePath } from "next/cache";
import { and, desc, eq, isNull } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { cliTokens, users } from "@/lib/db/schema";
import {
mintCliToken,
revokeCliToken,
CLI_TOKEN_TTL_SECONDS,
} from "@/lib/auth/cli-token";
import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody, CardHeader } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge";
import { EmptyState } from "@/app/_components/ui/empty-state";
import TokensManager from "./tokens-manager";
export const dynamic = "force-dynamic";
async function createTokenAction(_prev: { token: string | null; error: string | null }, formData: FormData): Promise<{ token: string | null; error: string | null }> {
"use server";
try {
const session = await auth();
if (!session?.user?.id) return { token: null, error: "not authenticated" };
const name = String(formData.get("name") ?? "").trim() || `Token ${new Date().toISOString().slice(0, 10)}`;
const userRow = await db
.select({
oidcIss: users.oidcIss,
oidcSub: users.oidcSub,
email: users.email,
name: users.name,
})
.from(users)
.where(eq(users.id, session.user.id))
.limit(1);
const u = userRow[0];
if (!u) return { token: null, error: "user row not found" };
const minted = await mintCliToken(
{
userId: session.user.id,
oidcIss: u.oidcIss,
oidcSub: u.oidcSub,
email: u.email,
name: u.name,
},
{ tokenName: name },
);
revalidatePath("/settings/tokens");
return { token: minted.token, error: null };
} catch (e) {
return { token: null, error: e instanceof Error ? e.message : "unknown error" };
}
}
async function revokeTokenAction(formData: FormData) {
"use server";
const session = await auth();
if (!session?.user?.id) throw new Error("not authenticated");
const tokenId = String(formData.get("tokenId") ?? "");
await revokeCliToken(session.user.id, tokenId);
revalidatePath("/settings/tokens");
}
export default async function TokensPage() {
const session = await auth();
const userId = session!.user.id;
const tokens = await db
.select({
id: cliTokens.id,
name: cliTokens.name,
jti: cliTokens.jti,
createdAt: cliTokens.createdAt,
lastUsedAt: cliTokens.lastUsedAt,
expiresAt: cliTokens.expiresAt,
revokedAt: cliTokens.revokedAt,
})
.from(cliTokens)
.where(eq(cliTokens.userId, userId))
.orderBy(desc(cliTokens.createdAt));
const active = tokens.filter((t) => !t.revokedAt && t.expiresAt > new Date());
const inactive = tokens.filter((t) => t.revokedAt || t.expiresAt <= new Date());
const ttlDays = Math.floor(CLI_TOKEN_TTL_SECONDS / 86400);
return (
<Container className="pt-6 max-w-3xl">
<PageHeader
title="CLI tokens"
description={`Long-lived bearer tokens for MCP clients without browser access. ${ttlDays}-day expiry per token.`}
/>
<Card className="mb-6">
<CardHeader className="text-sm font-medium text-fg">Generate a new token</CardHeader>
<CardBody>
<TokensManager action={createTokenAction} ttlDays={ttlDays} />
</CardBody>
</Card>
<h2 className="text-sm font-medium text-fg-muted mt-8 mb-2">Active tokens</h2>
{active.length === 0 ? (
<EmptyState title="No active tokens" description="Generate one above to connect a headless client." />
) : (
<Card>
{active.map((t, i) => (
<div
key={t.id}
className={`px-4 py-3 flex items-center gap-3 ${i > 0 ? "border-t border-border" : ""}`}
>
<div className="flex-1 min-w-0">
<div className="text-sm text-fg truncate">{t.name}</div>
<div className="text-xs text-fg-subtle">
Created {new Date(t.createdAt).toLocaleDateString()} ·{" "}
{t.lastUsedAt
? `last used ${new Date(t.lastUsedAt).toLocaleString()}`
: "never used"}
{" · "}expires {new Date(t.expiresAt).toLocaleDateString()}
</div>
</div>
<form action={revokeTokenAction}>
<input type="hidden" name="tokenId" value={t.id} />
<button
type="submit"
className="text-xs text-danger hover:underline"
>
Revoke
</button>
</form>
</div>
))}
</Card>
)}
{inactive.length > 0 ? (
<>
<h2 className="text-sm font-medium text-fg-muted mt-8 mb-2">Revoked / expired</h2>
<Card>
{inactive.map((t, i) => (
<div
key={t.id}
className={`px-4 py-3 flex items-center gap-3 ${i > 0 ? "border-t border-border" : ""}`}
>
<div className="flex-1 min-w-0">
<div className="text-sm text-fg-muted truncate">{t.name}</div>
<div className="text-xs text-fg-subtle">
{t.revokedAt
? `Revoked ${new Date(t.revokedAt).toLocaleString()}`
: `Expired ${new Date(t.expiresAt).toLocaleString()}`}
</div>
</div>
<Badge tone="danger">{t.revokedAt ? "revoked" : "expired"}</Badge>
</div>
))}
</Card>
</>
) : null}
</Container>
);
}
@@ -0,0 +1,67 @@
"use client";
import { useActionState } from "react";
import { Button } from "@/app/_components/ui/button";
import { Input, Label } from "@/app/_components/ui/input";
interface State {
token: string | null;
error: string | null;
}
interface Props {
action: (prev: State, formData: FormData) => Promise<State>;
ttlDays: number;
}
const initial: State = { token: null, error: null };
export default function TokensManager({ action, ttlDays }: Props) {
const [state, formAction, pending] = useActionState(action, initial);
if (state.token) {
return (
<div className="space-y-3">
<div className="text-sm text-success font-medium">
Token generated copy now, you won&apos;t see it again
</div>
<pre
className="!whitespace-pre-wrap !break-all select-all"
style={{ userSelect: "all" }}
>
{state.token}
</pre>
<details className="text-xs text-fg-muted">
<summary className="cursor-pointer">claude mcp add command</summary>
<pre className="mt-2">{`claude mcp add --transport http --scope user \\
--header "Authorization: Bearer ${state.token}" \\
shared-memory https://memory.dnspegasus.net/api/mcp`}</pre>
</details>
<p className="text-xs text-fg-subtle">
Valid for {ttlDays} days. Revoke individually below if it leaks.
</p>
</div>
);
}
return (
<form action={formAction} className="flex flex-wrap items-end gap-3">
<div className="flex-1 min-w-[200px]">
<Label htmlFor="name" hint="optional">Token name</Label>
<Input
id="name"
name="name"
placeholder="e.g. Laptop, Headless CI, …"
className="mt-1"
autoComplete="off"
/>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Generating…" : "Generate token"}
</Button>
{state.error ? (
<p className="basis-full text-sm text-danger">error: {state.error}</p>
) : null}
</form>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { HTMLAttributes } from "react";
type Tone = "neutral" | "accent" | "success" | "warning" | "danger";
const tones: Record<Tone, string> = {
neutral: "bg-surface-3 text-fg-muted",
accent: "bg-accent-500/15 text-accent-300",
success: "bg-success/15 text-success",
warning: "bg-warning/15 text-warning",
danger: "bg-danger/15 text-danger",
};
export interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {
tone?: Tone;
}
export function Badge({ tone = "neutral", className = "", ...rest }: BadgeProps) {
return (
<span
className={
"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-sm " +
"text-[11px] font-medium leading-none whitespace-nowrap " +
`${tones[tone]} ${className}`
}
{...rest}
/>
);
}
+46
View File
@@ -0,0 +1,46 @@
import type { ButtonHTMLAttributes } from "react";
type Variant = "primary" | "secondary" | "ghost" | "danger";
type Size = "sm" | "md";
const base =
"inline-flex items-center justify-center gap-1.5 rounded-md font-medium " +
"transition-colors disabled:opacity-50 disabled:cursor-not-allowed " +
"whitespace-nowrap select-none";
const variants: Record<Variant, string> = {
primary:
"bg-accent-500 text-white hover:bg-accent-400 active:bg-accent-600",
secondary:
"bg-surface-2 text-fg border border-border hover:border-border-strong hover:bg-surface-3",
ghost:
"bg-transparent text-fg hover:bg-surface-2",
danger:
"bg-transparent text-danger border border-border hover:bg-danger/10 hover:border-danger/60",
};
const sizes: Record<Size, string> = {
sm: "h-7 px-2.5 text-[13px]",
md: "h-9 px-3.5 text-sm",
};
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: Variant;
size?: Size;
}
export function Button({
variant = "primary",
size = "md",
className = "",
type = "button",
...rest
}: ButtonProps) {
return (
<button
type={type}
className={`${base} ${variants[variant]} ${sizes[size]} ${className}`}
{...rest}
/>
);
}
+32
View File
@@ -0,0 +1,32 @@
import type { HTMLAttributes } from "react";
export function Card({
className = "",
...rest
}: HTMLAttributes<HTMLDivElement>) {
return (
<div
className={`rounded-lg bg-surface-1 border border-border overflow-hidden ${className}`}
{...rest}
/>
);
}
export function CardBody({
className = "",
...rest
}: HTMLAttributes<HTMLDivElement>) {
return <div className={`p-4 ${className}`} {...rest} />;
}
export function CardHeader({
className = "",
...rest
}: HTMLAttributes<HTMLDivElement>) {
return (
<div
className={`px-4 py-3 border-b border-border bg-surface-2 ${className}`}
{...rest}
/>
);
}
+32
View File
@@ -0,0 +1,32 @@
import type { HTMLAttributes } from "react";
export function Container({
className = "",
...rest
}: HTMLAttributes<HTMLDivElement>) {
return (
<div className={`max-w-5xl mx-auto px-4 sm:px-6 ${className}`} {...rest} />
);
}
export function PageHeader({
title,
description,
actions,
}: {
title: string;
description?: React.ReactNode;
actions?: React.ReactNode;
}) {
return (
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3 mb-6">
<div>
<h1 className="text-2xl font-semibold text-fg tracking-tight">{title}</h1>
{description ? (
<p className="text-sm text-fg-muted mt-1">{description}</p>
) : null}
</div>
{actions ? <div className="flex gap-2">{actions}</div> : null}
</div>
);
}
@@ -0,0 +1,21 @@
import type { ReactNode } from "react";
export function EmptyState({
title,
description,
action,
}: {
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="border border-dashed border-border rounded-lg p-8 text-center">
<p className="text-fg font-medium">{title}</p>
{description ? (
<p className="text-sm text-fg-muted mt-1">{description}</p>
) : null}
{action ? <div className="mt-4 flex justify-center">{action}</div> : null}
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import type { InputHTMLAttributes, TextareaHTMLAttributes } from "react";
const field =
"block w-full rounded-md bg-surface-1 border border-border " +
"text-fg placeholder:text-fg-subtle " +
"focus:border-accent-400 focus:outline-none " +
"disabled:opacity-50 transition-colors";
export function Input({
className = "",
...rest
}: InputHTMLAttributes<HTMLInputElement>) {
return <input className={`${field} h-9 px-3 text-sm ${className}`} {...rest} />;
}
export function Textarea({
className = "",
rows = 6,
...rest
}: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return (
<textarea
rows={rows}
className={`${field} py-2 px-3 text-sm leading-relaxed font-mono ${className}`}
{...rest}
/>
);
}
export function Label({
htmlFor,
children,
hint,
}: {
htmlFor?: string;
children: React.ReactNode;
hint?: string;
}) {
return (
<label htmlFor={htmlFor} className="block">
<span className="text-sm font-medium text-fg">{children}</span>
{hint ? <span className="ml-2 text-xs text-fg-subtle">{hint}</span> : null}
</label>
);
}
-61
View File
@@ -1,61 +0,0 @@
"use client";
import { useActionState } from "react";
interface State {
token: string | null;
error: string | null;
}
interface Props {
action: (prev: State) => Promise<State>;
ttlDays: number;
}
const initial: State = { token: null, error: null };
export default function ConnectForm({ action, ttlDays }: Props) {
const [state, formAction, pending] = useActionState(action, initial);
return (
<section style={{ marginTop: "2rem" }}>
{state.token ? (
<>
<h2 style={{ color: "#7ee787" }}>
New token (copy now won&apos;t be shown again)
</h2>
<pre
style={{
whiteSpace: "pre-wrap",
wordBreak: "break-all",
userSelect: "all",
}}
>
{state.token}
</pre>
<h3>Add to Claude Code</h3>
<pre>{`claude mcp add --transport http \\
--header "Authorization: Bearer ${state.token}" \\
shared-memory https://memory.dnspegasus.net/api/mcp`}</pre>
<p className="muted">
Valid for {ttlDays} days. To revoke all outstanding CLI tokens at
once, rotate <code>CLI_TOKEN_SECRET</code> on the server.
</p>
</>
) : (
<form action={formAction}>
<button type="submit" disabled={pending}>
{pending ? "Generating…" : "Generate token"}
</button>
{state.error ? (
<p style={{ color: "#ff6b6b" }}>error: {state.error}</p>
) : null}
<p className="muted" style={{ marginTop: "0.75rem" }}>
Tokens carry your full Authentik identity. Valid for {ttlDays}{" "}
days. Treat them like a password.
</p>
</form>
)}
</section>
);
}
+4 -68
View File
@@ -1,73 +1,9 @@
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { mintCliToken, CLI_TOKEN_TTL_SECONDS } from "@/lib/auth/cli-token";
import ConnectForm from "./connect-form";
export const dynamic = "force-dynamic";
/**
* Server action — mints a fresh CLI token for the currently signed-in user.
*
* Returned via useActionState to the client; the token only ever exists in
* React state, never in the URL or a persisted cookie.
*/
async function generateToken(_prev: { token: string | null; error: string | null }) {
"use server";
try {
const session = await auth();
if (!session?.user?.id) return { token: null, error: "not authenticated" };
const row = await db
.select({
oidcIss: users.oidcIss,
oidcSub: users.oidcSub,
email: users.email,
name: users.name,
})
.from(users)
.where(eq(users.id, session.user.id))
.limit(1);
const u = row[0];
if (!u) return { token: null, error: "user row not found" };
const token = await mintCliToken({
oidcIss: u.oidcIss,
oidcSub: u.oidcSub,
email: u.email,
name: u.name,
});
return { token, error: null };
} catch (e) {
return { token: null, error: e instanceof Error ? e.message : "unknown error" };
}
}
export default async function ConnectPage() {
const session = await auth();
if (!session?.user) {
redirect("/api/auth/signin?callbackUrl=/connect");
}
const ttlDays = Math.floor(CLI_TOKEN_TTL_SECONDS / 86400);
const userLabel = session.user.email ?? session.user.name ?? session.user.id;
return (
<main className="container">
<h1>Connect an MCP client</h1>
<p className="muted">
Generate a bearer token for pasting into Claude Code (or any MCP
client) when an OAuth loopback callback isn&apos;t practical for
example, a Claude Code instance running inside a container.
</p>
<p>
Signed in as <strong>{userLabel}</strong>.
</p>
<ConnectForm action={generateToken} ttlDays={ttlDays} />
</main>
);
// Legacy URL — moved to /settings/tokens in Phase 3b. Preserve old
// bookmarks and the existing instructions printed by older clients.
export default function ConnectRedirect() {
redirect("/settings/tokens");
}
+73 -48
View File
@@ -1,71 +1,96 @@
:root {
color-scheme: light dark;
--bg: #0b0d10;
--fg: #e7e9ec;
--muted: #8a9099;
--accent: #6ea8fe;
--surface: #14181d;
--border: #232a31;
@import "tailwindcss";
/* --------------------------------------------------------------------------
* Design tokens.
*
* Dark-first palette (the only theme right now). Light mode can come later
* by extending these tokens.
* -------------------------------------------------------------------------- */
@theme {
/* Brand */
--color-accent-300: oklch(0.79 0.13 250);
--color-accent-400: oklch(0.72 0.16 250);
--color-accent-500: oklch(0.65 0.19 250);
--color-accent-600: oklch(0.55 0.18 250);
/* Surface stack */
--color-bg: #0b0d10;
--color-surface-1: #11151b;
--color-surface-2: #161b22;
--color-surface-3: #1c222b;
/* Foreground */
--color-fg: #e7e9ec;
--color-fg-muted: #9aa3ad;
--color-fg-subtle: #6c7480;
/* Borders */
--color-border: #232a32;
--color-border-strong: #353c46;
/* Semantic */
--color-success: #5fd49d;
--color-danger: #ff6b6b;
--color-warning: #f5c071;
/* Radius */
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
--radius-lg: 0.625rem;
/* Font */
--font-sans:
ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
--font-mono:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
}
* {
box-sizing: border-box;
}
/* --------------------------------------------------------------------------
* Base layer — global styling reset (light layer over Tailwind's preflight)
* -------------------------------------------------------------------------- */
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;
background: var(--color-bg);
color: var(--color-fg);
font-family: var(--font-sans);
font-size: 15px;
line-height: 1.55;
min-height: 100%;
}
::selection {
background: color-mix(in srgb, var(--color-accent-500) 35%, transparent);
}
/* Avoid bright white default focus ring when using accent buttons. */
*:focus-visible {
outline: 2px solid var(--color-accent-400);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
a {
color: var(--accent);
color: var(--color-accent-300);
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);
code,
pre {
font-family: var(--font-mono);
}
pre {
background: var(--surface);
border: 1px solid var(--border);
background: var(--color-surface-1);
border: 1px solid var(--color-border);
padding: 1rem;
border-radius: 0.5rem;
border-radius: var(--radius-md);
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);
}
+3 -26
View File
@@ -1,31 +1,8 @@
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>
);
// Legacy URL — Phase 1's debug page. Replaced by /dashboard + /settings.
export default function MeRedirect() {
redirect("/dashboard");
}
+39 -26
View File
@@ -1,40 +1,53 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { auth } from "@/auth";
import { Button } from "@/app/_components/ui/button";
export const dynamic = "force-dynamic";
export default async function HomePage() {
const session = await auth();
// Signed-in users always go to the app; the landing is for anonymous
// visitors only.
if (session?.user) redirect("/dashboard");
return (
<main className="container">
<h1>shared-memory</h1>
<p className="muted">
Self-hosted MCP server providing shared persistent memory across Claude Code sessions.
</p>
<main className="min-h-screen flex items-center justify-center px-4">
<div className="max-w-xl w-full text-center space-y-6">
<div className="inline-flex items-center gap-2 text-fg-muted text-sm">
<span className="inline-block size-2 rounded-full bg-accent-400" />
shared-memory
</div>
{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>
)}
<h1 className="text-3xl sm:text-4xl font-semibold tracking-tight text-fg">
Shared, persistent memory<br />for every Claude Code session.
</h1>
<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. For containerized clients without OAuth loopback,{" "}
{session?.user ? (
<Link href="/connect">generate a CLI token </Link>
) : (
<>sign in and visit <code>/connect</code></>
)}
</p>
<p className="text-fg-muted max-w-md mx-auto">
A self-hosted MCP server that lets the Claude Codes on your laptop,
server, and any container share durable memories, scoped per
project or globally.
</p>
<div className="flex justify-center gap-3 pt-2">
<Link href="/api/auth/signin?callbackUrl=/dashboard" className="no-underline">
<Button>Sign in with OIDC</Button>
</Link>
<a
href="https://repo.anhonesthost.net/jknapp/shared-memory"
className="no-underline"
target="_blank"
rel="noreferrer"
>
<Button variant="secondary">Source</Button>
</a>
</div>
<p className="text-xs text-fg-subtle pt-6">
MCP endpoint at <code>/api/mcp</code> · OAuth discovery at{" "}
<code>/.well-known/oauth-protected-resource</code>
</p>
</div>
</main>
);
}
+24
View File
@@ -0,0 +1,24 @@
-- cli_tokens: registry of HMAC-signed tokens minted at /connect.
--
-- Each row corresponds to one issued JWT. The token's `jti` claim is the
-- unique identifier — we store the full jti, not a hash, since the jti
-- itself isn't a secret (it's just a UUID; the signing material is
-- CLI_TOKEN_SECRET).
--
-- Soft-delete via revoked_at — never DROP rows; audit value lasts past
-- the JWT's natural expiration.
CREATE TABLE "cli_tokens" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"user_id" uuid NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"jti" text NOT NULL UNIQUE,
"name" text NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT now(),
"last_used_at" timestamptz,
"expires_at" timestamptz NOT NULL,
"revoked_at" timestamptz
);
CREATE INDEX "cli_tokens_user_idx" ON "cli_tokens" ("user_id");
CREATE INDEX "cli_tokens_user_active_idx" ON "cli_tokens" ("user_id", "revoked_at")
WHERE "revoked_at" IS NULL;
+87 -13
View File
@@ -1,23 +1,30 @@
import { randomUUID } from "node:crypto";
import { SignJWT, jwtVerify, decodeProtectedHeader } from "jose";
import type { JWTPayload } from "jose";
import { and, eq, isNull } from "drizzle-orm";
import { env } from "@/lib/env";
import { db } from "@/lib/db/client";
import { cliTokens } from "@/lib/db/schema";
/**
* "CLI tokens" are HMAC-signed JWTs minted on demand from the /connect page
* after the user logs into the Web UI via Authentik. They're suitable for
* pasting into an MCP client's Authorization header on machines where the
* OAuth loopback callback isn't reachable (containers, headless setups).
* CLI tokens HMAC-signed JWTs minted from /settings/tokens (or the
* legacy /connect page) after the user logs into the Web UI via OIDC.
*
* Suitable for pasting into an MCP client's `Authorization` header on
* machines where the OAuth loopback callback isn't reachable.
*
* Trust model: we trust whoever holds CLI_TOKEN_SECRET. Verification is a
* local HMAC check — no JWKS roundtrip. To revoke ALL outstanding CLI
* tokens, rotate CLI_TOKEN_SECRET.
* local HMAC check — no JWKS round-trip — plus an opt-in revocation
* lookup in the `cli_tokens` table.
*
* The payload carries the user's real Authentik identity in `iss` + `sub`
* so the same `users` row resolution path works for both token kinds.
* - Tokens minted by mintCliToken always carry a `jti` claim and have a
* matching row in cli_tokens.
* - Tokens minted by an older version of this server have no `jti`. We
* accept them on signature validity alone until they expire naturally
* (max 30 days post-deploy). Their only revocation knob is rotating
* CLI_TOKEN_SECRET.
*
* Dispatch from the standard Authentik verifier is by the `kid` header:
* CLI tokens set `kid: "cli-v1"`, Authentik tokens carry whatever key id
* the JWKS published.
* To revoke a tracked token immediately, set cli_tokens.revoked_at.
*/
export const CLI_TOKEN_KID = "cli-v1";
@@ -29,14 +36,41 @@ function secret(): Uint8Array {
}
export interface CliTokenSubject {
userId: string;
oidcIss: string;
oidcSub: string;
email?: string | null;
name?: string | null;
}
export async function mintCliToken(subject: CliTokenSubject): Promise<string> {
return await new SignJWT({
export interface MintCliTokenOptions {
/** Human-readable label shown in the Settings UI. */
tokenName: string;
}
export interface MintCliTokenResult {
token: string;
jti: string;
expiresAt: Date;
}
export async function mintCliToken(
subject: CliTokenSubject,
options: MintCliTokenOptions,
): Promise<MintCliTokenResult> {
const jti = randomUUID();
const expiresAt = new Date(Date.now() + CLI_TOKEN_TTL_SECONDS * 1000);
// Record the issued token first so a crash mid-mint can't leak a usable
// token that isn't in our registry.
await db.insert(cliTokens).values({
userId: subject.userId,
jti,
name: options.tokenName,
expiresAt,
});
const token = await new SignJWT({
oidc_iss: subject.oidcIss,
oidc_sub: subject.oidcSub,
email: subject.email ?? undefined,
@@ -46,9 +80,12 @@ export async function mintCliToken(subject: CliTokenSubject): Promise<string> {
.setIssuer(CLI_TOKEN_ISSUER)
.setSubject(subject.oidcSub)
.setAudience(env().OIDC_AUDIENCE)
.setJti(jti)
.setIssuedAt()
.setExpirationTime(`${CLI_TOKEN_TTL_SECONDS}s`)
.sign(secret());
return { token, jti, expiresAt };
}
export interface CliClaims extends JWTPayload {
@@ -66,6 +103,31 @@ export async function verifyCliToken(token: string): Promise<CliClaims> {
if (typeof payload.oidc_iss !== "string" || typeof payload.oidc_sub !== "string") {
throw new Error("CLI token missing oidc_iss/oidc_sub claims");
}
// If the token carries a jti, enforce the revocation registry. Tokens
// minted before the registry existed have no jti — accept those on
// signature alone until natural expiration.
if (typeof payload.jti === "string") {
const rows = await db
.select({ id: cliTokens.id, revokedAt: cliTokens.revokedAt })
.from(cliTokens)
.where(eq(cliTokens.jti, payload.jti))
.limit(1);
const row = rows[0];
if (!row) {
throw new Error("CLI token not in registry — likely minted by another deployment");
}
if (row.revokedAt) {
throw new Error("CLI token revoked");
}
// Touch last_used_at — best-effort, don't fail the request if this errors.
void db
.update(cliTokens)
.set({ lastUsedAt: new Date() })
.where(eq(cliTokens.id, row.id))
.catch(() => {});
}
return payload as CliClaims;
}
@@ -78,3 +140,15 @@ export function tokenKid(token: string): string | undefined {
return undefined;
}
}
/** Revoke a token by id (owned by the given user). */
export async function revokeCliToken(userId: string, tokenId: string): Promise<boolean> {
const result = await db
.update(cliTokens)
.set({ revokedAt: new Date() })
.where(
and(eq(cliTokens.id, tokenId), eq(cliTokens.userId, userId), isNull(cliTokens.revokedAt)),
)
.returning({ id: cliTokens.id });
return result.length > 0;
}
+21
View File
@@ -126,6 +126,25 @@ export const snippets = pgTable(
}),
);
export const cliTokens = pgTable(
"cli_tokens",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
jti: text("jti").notNull().unique(),
name: text("name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
},
(t) => ({
userIdx: index("cli_tokens_user_idx").on(t.userId),
}),
);
export const auditLog = pgTable(
"audit_log",
{
@@ -158,5 +177,7 @@ export type Memory = typeof memories.$inferSelect;
export type NewMemory = typeof memories.$inferInsert;
export type Snippet = typeof snippets.$inferSelect;
export type NewSnippet = typeof snippets.$inferInsert;
export type CliToken = typeof cliTokens.$inferSelect;
export type NewCliToken = typeof cliTokens.$inferInsert;
export type AuditEntry = typeof auditLog.$inferSelect;
export type NewAuditEntry = typeof auditLog.$inferInsert;
+16 -108
View File
@@ -1,5 +1,5 @@
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { db, pg } from "@/lib/db/client";
import { db } from "@/lib/db/client";
import { memories, projects, auditLog } from "@/lib/db/schema";
import {
MemoryIdInput,
@@ -10,6 +10,7 @@ import {
ProjectIdentifyInput,
} from "@shared-memory/schemas";
import { embedText } from "@/lib/embedder";
import { searchMemories } from "@/lib/memories";
import type { UserContext } from "./context";
/**
@@ -62,11 +63,6 @@ async function resolveProjectId(
return row[0]?.id ?? null;
}
/** pgvector accepts vectors as text literals like "[0.1,0.2,...]". */
function toVectorLiteral(v: number[]): string {
return `[${v.join(",")}]`;
}
// ---------- tools ----------
const projectIdentify: ToolDef = {
@@ -368,13 +364,6 @@ const memoryUpdate: ToolDef = {
},
};
interface RankAccumulator {
vectorRank?: number;
ftsRank?: number;
tagRank?: number;
rrfScore: number;
}
const memorySearch: ToolDef = {
name: "memory.search",
description:
@@ -399,87 +388,21 @@ const memorySearch: ToolDef = {
? await resolveProjectId(ctx, parsed.data.project)
: null;
if (parsed.data.project && !projectId) {
return ok({ items: [], _ranks: {} }, "0 results (unknown project)");
return ok({ items: [], debug: { vec: 0, fts: 0, tag: 0 } }, "0 results (unknown project)");
}
const queryVec = await embedText(query);
const vecLit = toVectorLiteral(queryVec);
const CANDIDATES = 50;
const RRF_K = 60;
const result = await searchMemories(
ctx.userId,
query,
{ scope, projectKey: parsed.data.project, tags },
limit,
);
// Run the three candidate-fetch queries in parallel. The filter is
// expressed via pg's tagged-template binding so values are safely
// interpolated.
const userId = ctx.userId;
const vecPromise = pg<{ id: string }[]>`
SELECT id
FROM memories
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND embedding IS NOT NULL
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY embedding <=> ${vecLit}::vector ASC
LIMIT ${CANDIDATES}
`;
const ftsPromise = pg<{ id: string }[]>`
SELECT id
FROM memories, plainto_tsquery('english', ${query}) AS q
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND content_tsv @@ q
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY ts_rank_cd(content_tsv, q) DESC
LIMIT ${CANDIDATES}
`;
const tagPromise =
tags && tags.length > 0
? pg<{ id: string }[]>`
SELECT id
FROM memories
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND tags && ${tags}::text[]
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY cardinality(
ARRAY(SELECT unnest(tags) INTERSECT SELECT unnest(${tags}::text[]))
) DESC
LIMIT ${CANDIDATES}
`
: Promise.resolve([] as { id: string }[]);
const [vecHits, ftsHits, tagHits] = await Promise.all([
vecPromise,
ftsPromise,
tagPromise,
]);
// Fuse via RRF: score(d) = Σ_r 1/(k + rank_r(d))
const scores = new Map<string, RankAccumulator>();
const accum = (id: string, rank: number, key: "vectorRank" | "ftsRank" | "tagRank") => {
const e = scores.get(id) ?? { rrfScore: 0 };
e[key] = rank;
e.rrfScore += 1 / (RRF_K + rank);
scores.set(id, e);
};
vecHits.forEach((h, i) => accum(h.id, i + 1, "vectorRank"));
ftsHits.forEach((h, i) => accum(h.id, i + 1, "ftsRank"));
tagHits.forEach((h, i) => accum(h.id, i + 1, "tagRank"));
if (scores.size === 0) {
return ok({ items: [], debug: { vec: 0, fts: 0, tag: 0 } }, "0 results");
if (result.hits.length === 0) {
return ok({ items: [], debug: result.debug }, "0 results");
}
const sorted = [...scores.entries()]
.sort(([, a], [, b]) => b.rrfScore - a.rrfScore)
.slice(0, limit);
const topIds = sorted.map(([id]) => id);
const topIds = result.hits.map((h) => h.id);
const rows = await db
.select({
id: memories.id,
@@ -494,33 +417,18 @@ const memorySearch: ToolDef = {
.where(inArray(memories.id, topIds));
const byId = new Map(rows.map((r) => [r.id, r]));
const items = sorted.flatMap(([id, rank]) => {
const row = byId.get(id);
const items = result.hits.flatMap((hit) => {
const row = byId.get(hit.id);
if (!row) return [];
return [
{
...row,
_rank: {
rrfScore: Number(rank.rrfScore.toFixed(6)),
vectorRank: rank.vectorRank ?? null,
ftsRank: rank.ftsRank ?? null,
tagRank: rank.tagRank ?? null,
},
_rank: hit.rank,
},
];
});
return ok(
{
items,
debug: {
vec: vecHits.length,
fts: ftsHits.length,
tag: tagHits.length,
},
},
`${items.length} result(s)`,
);
return ok({ items, debug: result.debug }, `${items.length} result(s)`);
},
};
+148
View File
@@ -0,0 +1,148 @@
import { and, eq } from "drizzle-orm";
import { db, pg } from "@/lib/db/client";
import { projects } from "@/lib/db/schema";
import { embedText } from "@/lib/embedder";
/**
* Shared search helper. Used by:
* - the MCP `memory.search` tool (returns rich rank data for the model)
* - the Web UI memories page (renders human-readable results)
*
* Performs three candidate fetches in parallel — pgvector cosine, FTS
* ts_rank_cd, tag-set overlap — then fuses with Reciprocal Rank Fusion
* (k=60). Returns top-N with per-source rank info attached.
*/
export interface SearchFilters {
scope?: "project" | "user";
projectKey?: string;
tags?: string[];
}
export interface SearchHit {
id: string;
rank: {
rrfScore: number;
vectorRank: number | null;
ftsRank: number | null;
tagRank: number | null;
};
}
export interface SearchResult {
hits: SearchHit[];
debug: { vec: number; fts: number; tag: number };
}
const CANDIDATES = 50;
const RRF_K = 60;
function toVectorLiteral(v: number[]): string {
return `[${v.join(",")}]`;
}
async function resolveProjectId(
userId: string,
projectKey?: string,
): Promise<string | null> {
if (!projectKey) return null;
const row = await db
.select({ id: projects.id })
.from(projects)
.where(and(eq(projects.userId, userId), eq(projects.key, projectKey)))
.limit(1);
return row[0]?.id ?? null;
}
export async function searchMemories(
userId: string,
query: string,
filters: SearchFilters = {},
limit = 20,
): Promise<SearchResult> {
const { scope, projectKey, tags } = filters;
const projectId = projectKey ? await resolveProjectId(userId, projectKey) : null;
if (projectKey && !projectId) {
return { hits: [], debug: { vec: 0, fts: 0, tag: 0 } };
}
const queryVec = await embedText(query);
const vecLit = toVectorLiteral(queryVec);
const vecPromise = pg<{ id: string }[]>`
SELECT id
FROM memories
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND embedding IS NOT NULL
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY embedding <=> ${vecLit}::vector ASC
LIMIT ${CANDIDATES}
`;
const ftsPromise = pg<{ id: string }[]>`
SELECT id
FROM memories, plainto_tsquery('english', ${query}) AS q
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND content_tsv @@ q
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY ts_rank_cd(content_tsv, q) DESC
LIMIT ${CANDIDATES}
`;
const tagPromise =
tags && tags.length > 0
? pg<{ id: string }[]>`
SELECT id
FROM memories
WHERE user_id = ${userId}
AND deleted_at IS NULL
AND tags && ${tags}::text[]
${scope ? pg`AND scope = ${scope}` : pg``}
${projectId ? pg`AND project_id = ${projectId}` : pg``}
ORDER BY cardinality(
ARRAY(SELECT unnest(tags) INTERSECT SELECT unnest(${tags}::text[]))
) DESC
LIMIT ${CANDIDATES}
`
: Promise.resolve([] as { id: string }[]);
const [vec, fts, tag] = await Promise.all([vecPromise, ftsPromise, tagPromise]);
interface Accumulator {
vectorRank: number | null;
ftsRank: number | null;
tagRank: number | null;
rrfScore: number;
}
const scores = new Map<string, Accumulator>();
const accum = (id: string, rank: number, key: "vectorRank" | "ftsRank" | "tagRank") => {
const e =
scores.get(id) ??
({ vectorRank: null, ftsRank: null, tagRank: null, rrfScore: 0 } as Accumulator);
e[key] = rank;
e.rrfScore += 1 / (RRF_K + rank);
scores.set(id, e);
};
vec.forEach((h, i) => accum(h.id, i + 1, "vectorRank"));
fts.forEach((h, i) => accum(h.id, i + 1, "ftsRank"));
tag.forEach((h, i) => accum(h.id, i + 1, "tagRank"));
const hits = [...scores.entries()]
.sort(([, a], [, b]) => b.rrfScore - a.rrfScore)
.slice(0, limit)
.map(([id, rank]) => ({
id,
rank: {
rrfScore: Number(rank.rrfScore.toFixed(6)),
vectorRank: rank.vectorRank,
ftsRank: rank.ftsRank,
tagRank: rank.tagRank,
},
}));
return { hits, debug: { vec: vec.length, fts: fts.length, tag: tag.length } };
}
+184
View File
@@ -0,0 +1,184 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { and, eq, isNull } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects, auditLog } from "@/lib/db/schema";
import { embedText } from "@/lib/embedder";
import {
MemoryWriteInput,
MemoryUpdateInput,
MemoryIdInput,
} from "@shared-memory/schemas";
/**
* Server Actions for memory CRUD from the Web UI. Mirrors the MCP tools
* but writes through the same DB layer, so updates and deletes here are
* indistinguishable from those made via Claude Code.
*
* `actor` is "web" in audit_log so we can tell the two paths apart later.
*/
async function requireUserId(): Promise<string> {
const session = await auth();
if (!session?.user?.id) throw new Error("not authenticated");
return session.user.id;
}
async function resolveProjectId(userId: string, key: string): Promise<string | null> {
const row = await db
.select({ id: projects.id })
.from(projects)
.where(and(eq(projects.userId, userId), eq(projects.key, key)))
.limit(1);
return row[0]?.id ?? null;
}
async function upsertProject(
userId: string,
key: string,
displayName?: string,
): Promise<string> {
const existing = await resolveProjectId(userId, key);
if (existing) return existing;
const row = await db
.insert(projects)
.values({ userId, key, displayName: displayName ?? null })
.returning({ id: projects.id });
return row[0]!.id;
}
function parseTags(raw: FormDataEntryValue | null): string[] {
if (typeof raw !== "string") return [];
return raw
.split(/[,\s]+/)
.map((t) => t.trim())
.filter((t) => t.length > 0);
}
export async function createMemoryAction(formData: FormData) {
const userId = await requireUserId();
const payload = {
content: String(formData.get("content") ?? "").trim(),
scope: (formData.get("scope") as "project" | "user") || "project",
project: (formData.get("project") as string | null)?.trim() || undefined,
tags: parseTags(formData.get("tags")),
};
const parsed = MemoryWriteInput.safeParse(payload);
if (!parsed.success) {
throw new Error(parsed.error.issues.map((i) => i.message).join("; "));
}
let projectId: string | null = null;
if (parsed.data.scope === "project") {
if (!parsed.data.project) throw new Error("scope=project requires `project`");
projectId = await upsertProject(userId, parsed.data.project);
}
const embedding = await embedText(parsed.data.content);
const inserted = await db
.insert(memories)
.values({
userId,
projectId,
scope: parsed.data.scope,
content: parsed.data.content,
tags: parsed.data.tags ?? [],
embedding,
})
.returning({ id: memories.id });
await db.insert(auditLog).values({
userId,
actor: "web",
action: "memory.write",
entityType: "memory",
entityId: inserted[0]!.id,
payload: {
scope: parsed.data.scope,
projectKey: parsed.data.project ?? null,
tags: parsed.data.tags ?? [],
},
});
revalidatePath("/memories");
redirect(`/memories/${inserted[0]!.id}`);
}
export async function updateMemoryAction(formData: FormData) {
const userId = await requireUserId();
const id = String(formData.get("id") ?? "");
const payload = {
id,
content: ((formData.get("content") as string | null) ?? "").trim() || undefined,
tags: parseTags(formData.get("tags")),
};
const parsed = MemoryUpdateInput.safeParse(payload);
if (!parsed.success) {
throw new Error(parsed.error.issues.map((i) => i.message).join("; "));
}
const existing = await db
.select({ id: memories.id, content: memories.content })
.from(memories)
.where(
and(eq(memories.id, parsed.data.id), eq(memories.userId, userId), isNull(memories.deletedAt)),
)
.limit(1);
if (!existing[0]) throw new Error("not found");
const update: Record<string, unknown> = { updatedAt: new Date() };
if (parsed.data.tags !== undefined) update.tags = parsed.data.tags;
if (parsed.data.content !== undefined && parsed.data.content !== existing[0].content) {
update.content = parsed.data.content;
update.embedding = await embedText(parsed.data.content);
}
await db.update(memories).set(update).where(eq(memories.id, parsed.data.id));
await db.insert(auditLog).values({
userId,
actor: "web",
action: "memory.update",
entityType: "memory",
entityId: parsed.data.id,
payload: { fields: Object.keys(update).filter((k) => k !== "updatedAt") },
});
revalidatePath(`/memories/${parsed.data.id}`);
revalidatePath("/memories");
redirect(`/memories/${parsed.data.id}`);
}
export async function deleteMemoryAction(formData: FormData) {
const userId = await requireUserId();
const id = String(formData.get("id") ?? "");
const parsed = MemoryIdInput.safeParse({ id });
if (!parsed.success) throw new Error(parsed.error.issues[0]!.message);
const updated = await db
.update(memories)
.set({ deletedAt: new Date() })
.where(
and(eq(memories.id, parsed.data.id), eq(memories.userId, userId), isNull(memories.deletedAt)),
)
.returning({ id: memories.id });
if (!updated[0]) throw new Error("not found");
await db.insert(auditLog).values({
userId,
actor: "web",
action: "memory.delete",
entityType: "memory",
entityId: updated[0].id,
});
revalidatePath("/memories");
redirect("/memories");
}
+2
View File
@@ -29,10 +29,12 @@
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"@tailwindcss/postcss": "^4.0.0",
"drizzle-kit": "^0.30.1",
"esbuild": "^0.24.2",
"eslint": "^9.17.0",
"eslint-config-next": "^15.1.0",
"tailwindcss": "^4.0.0",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
}
+5
View File
@@ -0,0 +1,5 @@
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};